Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables within object operators

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.

like image 355
Ryan D.W. Avatar asked Jul 24 '11 01:07

Ryan D.W.


1 Answers

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};
like image 148
cwallenpoole Avatar answered Nov 15 '22 16:11

cwallenpoole