对象运算符内的变量

发布于 2024-11-25 22:19:43 字数 494 浏览 2 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉薄对峙 2024-12-02 22:19:43

基本上你可以这样做,但你必须把括号放在外面。

$var1 = 'parent';
$var2 = 'available_from';
$keyValuePairs[$key] = $item->{$var1}()->{$var2};
// or $keyValuePairs[$key] = $item->$var1()->{$var2};

如果不使用 eval 基本上就没有办法解决这个问题:

// escape the first $
$keyValuePairs[$key] = eval( "\$item->$var1->$var2" );

但是,如果您首先可以访问潜在的变量集,那么实际上没有理由使用 eval。

你可以做这样的事情来解决它:

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};

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};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文