我可以自由地为php中不存在或未知的成员分配一些东西吗?成员名称和关联数组索引之间有什么区别吗?
之间有什么区别吗
$a = array();
$a['foo'] = 'something';
和
$a->foo = 'something';
如果存在差异,那么我如何创建"空"对象并向其动态添加成员?
您正在混合数组(数据的袋子/容器)和对象(具有语义和功能的数据包装)。
阵列访问
第一个是正确的,因为您使用的数组在其他语言中的作用类似于HashTable或Dictionary。
$a = array(); // create an empty "box"
$a['foo'] = 'something'; // add something to this array
对象访问
第二种是Object访问。你会使用这样的东西:
class Foo {
public $foo;
}
$a = new Foo();
$a->foo = 'something';
尽管在这种情况下更好的用法是使用这样的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());
PHP魔术
然而,仍然可以选择使用PHPs魔术方法来创建像你描述的那样的行为。尽管如此,这应该被认为不是将数据存储到对象的常见方式,因为这会导致错误,并使你在(单元)测试中更加困难。
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
希望这能帮助你解决问题。
如果您想像在关联数组上那样为对象分配任意成员,您可能需要研究PHP的神奇属性重载。
下面是一个示例类,它只允许您分配和检索变量(主要取自PHP文档):
<?php
class PropertyTest
{
/** Location for overloaded data. */
private $data = array();
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __get($key) {
return $this->data[$key];
}
}
// sample use:
$a = new PropertyTest();
$a->foo = "bar";
echo $a->foo; // will print "bar"
?>
您可以创建一个空的类对象,然后向其添加属性,例如:
<?php
$myObject = new StdClass();
$myObject->id = 1;
$myObject->name = "Franky";
$myObject->url = "http://www.google.com";
var_dump($myObject);
这应该会产生
object(stdClass)#1 (3) { ["id"]=> int(1) ["name"]=> string(6) "Franky" ["url"]=> string(21) "http://www.google.com" }
就我个人而言,我更喜欢使用对象类而不是数组。