是否可以动态添加成员到PHP对象?

Is it possible to add to PHP objects on the fly? Say I have this code:

$foo = stdObject();
$foo->bar = 1337;

Is this valid PHP?

That's technically not valid code. Try something like:

$foo = new stdClass();
$foo->bar = 1337;
var_dump($foo);

http://php.net/manual/en/language.types.object.php

Yes it is. The only problem in your code is that it's missing a new before calling stdClass, and you're using stdObject, but you mean 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."
";

It is valid as long as you use valid class eg stdClass instead of stdObject:

$foo = new stdClass();
$foo->bar = 1337;
echo $foo->bar; // outputs 1337

You had these problems:

  • Using stdObject instead of stdClass
  • Not instantiating your object using new keyword

More Info:

You're close.

$foo = stdObject();

This needs to be:

$foo = new stdClass();

Then it will work.