gpt4 book ai didi

在临时对象上调用方法的 PHP 语法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:51:35 25 4
gpt4 key购买 nike

有没有一种方法可以在临时声明的对象上调用方法,而不必强制将第一个对象分配给变量?

见下文:

class Test
{
private $i = 7;
public function get() {return $this->i;}
}

$temp = new Test();
echo $temp->get(); //ok

echo new Test()->get(); //invalid syntax
echo {new Test()}->get(); //invalid syntax
echo ${new Test()}->get(); //invalid syntax

最佳答案

当我想要这种行为时,我使用以下解决方法。

我声明这个函数(在全局范围内):

function take($that) { return $that; }

然后我这样使用它:

echo take(new Test())->get();

关于在临时对象上调用方法的 PHP 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2217648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com