对象运算符中的变量 [英] Variables within object operators
问题描述
我正在尝试在PHP中设置基于变量的对象运算符,但只能在有限的范围内完成我要寻找的内容.例如,以下代码允许选择变量:
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};
和
$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};
如果不使用eval,基本上是没有办法解决的:
And there basically is no way of getting around that without using eval:
// escape the first $
$keyValuePairs[$key] = eval( "\$item->$var1->$var2" );
但是,如果您首先可以访问潜在的变量集,那么实际上没有理由使用eval.
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};
这篇关于对象运算符中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!