Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以向PHP对象动态添加成员?_Php - Fatal编程技术网

是否可以向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

是否可以动态添加到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 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
      不是一个函数