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);
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:
stdObject
instead of stdClass
new
keywordMore Info:
You're close.
$foo = stdObject();
This needs to be:
$foo = new stdClass();
Then it will work.