Mar*_*aio 4 php oop temporary object
有没有办法在临时声明的对象上调用方法而不必强制将第一个对象分配给变量?
见下文:
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
Run Code Online (Sandbox Code Playgroud)
小智 8
当我想要这种行为时,我使用以下解决方法.
我声明了这个函数(在全局范围内):
function take($that) { return $that; }
Run Code Online (Sandbox Code Playgroud)
然后我这样使用它:
echo take(new Test())->get();
Run Code Online (Sandbox Code Playgroud)
你能做的是
class Test
{
private $i = 7;
public function get() {return $this->i;}
public static function getNew() { return new self(); }
}
echo Test::getNew()->get();
Run Code Online (Sandbox Code Playgroud)