Suz*_*ioc 2 php arrays class object
我可以自由地为PHP中不存在或不存在的成员分配一些东西吗?成员名称和关联数组索引之间有什么区别吗?
我之间有任何区别
$a = array();
$a['foo'] = 'something';
Run Code Online (Sandbox Code Playgroud)
和
$a->foo = 'something';
Run Code Online (Sandbox Code Playgroud)
如果存在差异,那么如何创建"空"对象并动态添加成员呢?
您正在混合Arrays(它们是数据的包/容器)和Object(它们是具有语义含义和功能的数据包装).
第一个是正确的,因为您使用的数组就像其他语言中的HashTable或Dictionary一样.
$a = array(); // create an empty "box"
$a['foo'] = 'something'; // add something to this array
Run Code Online (Sandbox Code Playgroud)
第二个是对象访问.你会使用这样的东西:
class Foo {
public $foo;
}
$a = new Foo();
$a->foo = 'something';
Run Code Online (Sandbox Code Playgroud)
虽然在这种情况下更好的用法是使用这样的setter/getter方法.
class Foo {
private $foo;
public function setFoo($value) {
$this->foo = $value;
}
public function getFoo() {
return $this->foo;
}
}
$a = new Foo();
$a->setFoo('something');
var_dump($a->getFoo());
Run Code Online (Sandbox Code Playgroud)
但是,仍然可以选择使用PHPs Magic Methods来创建您描述的行为.然而,这应该被认为不是通常的方式将数据存储到对象,因为这会导致错误,并使您(单元)测试更加困难.
class Foo {
private $data = array();
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __get($key) {
return $this->data[$key];
}
}
$a = new Foo();
$a->foo = 'something'; // this will call the magic __set() method
var_dump($a->foo) // this will call the magic __get() method
Run Code Online (Sandbox Code Playgroud)
这有希望帮助您解决问题.