是否可以向PHP对象动态添加成员?
是否可以动态添加到PHP对象?假设我有这个代码:是否可以向PHP对象动态添加成员?,php,Php,是否可以动态添加到PHP对象?假设我有这个代码: $foo = stdObject(); $foo->bar = 1337; 这是有效的PHP吗?是的。代码中唯一的问题是在调用stdClass之前缺少一个new,您使用的是stdObject,但您的意思是stdClass <?php class A { public $foo = 1; } $a = new A; $b = $a; // $a and $b are copies of the same iden
$foo = stdObject();
$foo->bar = 1337;
这是有效的PHP吗?是的。代码中唯一的问题是在调用
stdClass
之前缺少一个new
,您使用的是stdObject
,但您的意思是stdClass
<?php
class A {
public $foo = 1;
}
$a = new A;
$b = $a; // $a and $b are copies of the same identifier
// ($a) = ($b) = <id>
$b->newProp = 2;
echo $a->newProp."\n";
这在技术上是无效的代码。尝试以下方法:
$foo = new stdClass();
$foo->bar = 1337;
var_dump($foo);
只要您使用有效的类,例如stdClass
而不是stdObject
,它就是有效的:
$foo = new stdClass();
$foo->bar = 1337;
echo $foo->bar; // outputs 1337
您遇到了以下问题:
- 使用
stdObject
而不是stdClass
- 不使用
new
关键字实例化对象
更多信息:
你很接近了
$foo = stdObject();
这需要:
$foo = new stdClass();
然后它就可以工作了。如果你的代码是$foo=new stdClass()代码>stdClass
不是一个函数