PHP Tip : Access object properties dynamically


If you want to pass a string into a function and use that string as the property of an object to get the value of that property you can use the following syntax.

function getObjectValueDynamically ($property_to_access) {
$value = $object->{$property_to_access};
return $value;
}

The part that you need to note here is, the parameter is surrounded by two Curly brackets like,

$object->{$property_to_access}
Advertisements

Let me know what you think .. :)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s