10

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.

2
  • 1
    From your last snippet: $keyValuePairs[$key] = $item->{$var1}()->{$var2}; should work. Have you tried taking the parentheses out of the string? Commented Jul 24, 2011 at 1:08
  • What are the actual error messages you're getting? Can you elaborate on "fail" a bit further? What does fail, what did you expect? Which part does not what you want? Commented Jul 24, 2011 at 1:08

1 Answer 1

29

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};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.