PHP: Using variables for calling object properties

Posted on: Jul 09, 2009 by wenbert

I had a scenario at work today that need me to use a variable in an object and call it like I would when using keys in an array.

Like when I have an array, I would do something like this:

$foo = array("apple" => "Hello World!");
$bar = "apple";
echo $foo[$bar]; //OUTPUT: Hello World!

I was able to use a variable for an object property by simply using $variable.

$obj = new stdClass();
$obj->bar= 'Hello World!';
$foo = "bar";
echo $obj->$foo; //OUTPUT: Hello World!

I thought it would spit out an error. But it didn’t :P


Subscribe to comments Comment | Trackback |
Post Tags: , , ,

Browse Timeline


Comments ( 5 )

i think it’s the same way we use to write code for the “magic” methods __set()/__get() in a class, but used from an out-of-the-class perspective, isn’t it?

seralf added these pithy words on Jul 09 09 at 8:17 PM

@seralf yup :-) I was chatting with my friend about this. And then the __set()/__get magic methods popped out of my head.

Wenbert added these pithy words on Jul 09 09 at 9:17 PM

Sure it works ;-)


$o = new StdClass();
$o->{"var" . substr("variable", 3)} = 'value';
echo $o->variable; // outputs: "value"

Aleksandr Tsertkov added these pithy words on Jul 10 09 at 4:09 AM

Stop using that in examples, it encourages deadshits to use it thus creating even more unmaintainable code!

Aleksandr Tsertkov's mum added these pithy words on Jul 10 09 at 11:57 AM

It is needed at some points, so why not give the coder the tools and let him decide what’s best for him?

fealls added these pithy words on Aug 22 09 at 2:27 PM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!