Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
实例化时对PHP类成员的访问_Php_Oop - Fatal编程技术网

实例化时对PHP类成员的访问

实例化时对PHP类成员的访问,php,oop,Php,Oop,我对PHP5.4的新语法有一个问题 实例化时具有成员访问权限的我的代码 $oClass = (new Foo)->bar(); $oClass->bar2(); 我得到这个错误 致命错误:对非对象调用成员函数bar2() 为什么? 编辑:我添加了返回$this现在可以工作了我猜您认为$oClass将包含一个对象。事实并非如此;它包含函数bar()的结果 如果要访问bar2(),您需要正常执行以下操作: $oClass = new Foo; $oClass->bar(); $o

我对PHP5.4的新语法有一个问题 实例化时具有成员访问权限的我的代码

$oClass = (new Foo)->bar();
$oClass->bar2();
我得到这个错误

致命错误:对非对象调用成员函数bar2()

为什么?


编辑:我添加了
返回$this现在可以工作了

我猜您认为
$oClass
将包含一个对象。事实并非如此;它包含函数
bar()
的结果

如果要访问
bar2()
,您需要正常执行以下操作:

$oClass = new Foo;
$oClass->bar();
$oClass->bar2();
实例化时的类成员访问适用于只需要访问对象的单个成员,然后就不再需要该对象的情况

编辑:
我可能忽略了什么

考虑以下代码:

class Test {
    public function foo() {
        return $this;
    }

    public function bar() {
        return 'oh hai';
    }
}

$t = (new Test)->foo();

print $t->bar();
在这种情况下,您仍然可以访问该对象,因为函数
foo()
返回
$this
,并且您正在存储它,以保持对该对象的引用

如果确实需要,还可以像这样链接方法:

print (new Test)->foo()->bar();
这个怎么样

($oClass = new Foo)->bar();
$oClass->bar2();

(new Foo)->bar()
的计算结果是什么?请不要编辑您的问题,而是接受您的同行在此网站上提供的以下答案。这也会将您的问题标记为已解决。解析错误。在作为答案提供代码之前,应该先尝试一下。