对象运算符内的变量
我正在尝试在 PHP 中设置一个基于变量的对象运算符,但只能在有限的范围内完成我正在寻找的目标。例如,以下代码允许变量选择:
$var1 = 'available_from';
$keyValuePairs[$key] = $item->parent()->{$var1};
但是,如果我想让父选择器也成为变量,我似乎不再能够这样做。以下两种方法都会失败:
$var1 = 'parent()->available_from';
$keyValuePairs[$key] = $item->{$var1};
并且
$var1 = 'parent()';
$var2 = 'available_from';
$keyValuePairs[$key] = $item->{$var1}->{$var2};
因此问题是是否有办法做到这一点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上你可以这样做,但你必须把括号放在外面。
如果不使用 eval 基本上就没有办法解决这个问题:
但是,如果您首先可以访问潜在的变量集,那么实际上没有理由使用 eval。
你可以做这样的事情来解决它:
You can basically do that, but you have to put the parens on the outside.
And there basically is no way of getting around that without using 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: