PHP: Dynamically refer to an object property

Sometimes you may need to programmatically determine which property of an object you would like to call. Are you trying to dynamically refer to an object property?

In order to do this, you need to get past an issue with ambiguity.

The PHP documentations says:

…if you write$$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable.

PHP has a simple way of dealing with this.

The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

So if you have an object with a variable property, you can write like this:

$object->{$property}[0]

//Or like this
$object->{$property[0]}

 

 

Posted in

Leave a Reply

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