I’m attempting to set up a variable-based object operator in PHP, but am only able to accomplish what I am looking for to a limited extent. For example, the following code allows for variable selection:
$var1 = 'available_from';
$keyValuePairs[$key] = $item->parent()->{$var1};
However, if I want to make the parent selector a variable as well, I no longer seem to be able to. Both of the following methods fail:
$var1 = 'parent()->available_from';
$keyValuePairs[$key] = $item->{$var1};
and
$var1 = 'parent()';
$var2 = 'available_from';
$keyValuePairs[$key] = $item->{$var1}->{$var2};
So the question is whether there is a way to do this.
You can basically do that, but you have to put the parens on the outside.
$var1 = 'parent';
$var2 = 'available_from';
$keyValuePairs[$key] = $item->{$var1}()->{$var2};
// or $keyValuePairs[$key] = $item->$var1()->{$var2};
And there basically is no way of getting around that without using eval:
// escape the first $
$keyValuePairs[$key] = eval( "\$item->$var1->$var2" );
But, there is really no reason to use eval if you have access to the potential set of variables first.
You can do something like this to get around it:
function call_or_return( $obj, $prop )
{
// test to see if it is a method (you'll need to remove the parens first)
$arr = array( $obj, $prop );
// if so call it.
if( is_callable( $arr ) ) return call_user_func( $arr );
// otherwise return it as a property
return $obj->$prop;
}
call_or_return( $item, $var1 )->{$var2};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With