2

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?

1
  • Your code would work if it said $foo = new stdClass(); stdClass is not a function Commented Jun 26, 2012 at 17:55

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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:

Comments

0

You're close.

$foo = stdObject();

This needs to be:

$foo = new stdClass();

Then it will work.

Comments

0

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."\n";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.