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 an object property with a dash

Earlier at home, I recently encountered this problem when I was using Zend_Service_Twitter to get the rateLimitStatus of API calls. One of the values returned by the successful API call contained a dash(-); I needed to do something like this to retrieve the value but it would always display “0″.

echo $twitter_response->reset-time; //note the dash(-) between reset and time ;-)

…the var_dump() looked like this:

['reset-time'] => 'Next year... :P'

Right now, I am at work and decided to re-create the scenario that happened earlier. Here is how I made it work:

$obj = new stdClass();
$prop = 'foo-bar';
$obj->$prop = 'Hello World';
echo $obj->foo-bar; //would echo 0
echo $obj->$prop; //Correct! Echoes "Hello World!"

I just stored the ‘foo-bar’ string into a variable ($prop) and used $obj->$prop to display the correct values.

If you have anything better, like not using a variable to hold the string value with the dash, please do post it below.

Pete Shaw, would do it like this:

echo $obj->{'foo-bar'};
This entry was posted in General and tagged , , , , . Bookmark the permalink.

2 Responses to PHP: Using an object property with a dash

  1. Pete Shaw says:


    …would be how I’d do it

  2. Wenbert says:

    @Pete Shaw, awesome! I am updating the post. Thanks! ;-)

Leave a 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>