A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

PHP: Using variables for calling object properties

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

This entry was posted in General and tagged , , , . Bookmark the permalink.

5 Responses to PHP: Using variables for calling object properties

  1. seralf says:

    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?

  2. Wenbert says:

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

  3. Sure it works ;-)


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

  4. Aleksandr Tsertkov's mum says:

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

  5. fealls says:

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

Leave a Reply to Aleksandr Tsertkov's mum Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>