PHP赋值返回值

时间:2013-10-18 13:07:30

标签: php syntax-error

假设您可以在PHP5.4中执行(new Object)->method() +我想知道为什么我不能这样做:

<?php

class Item {
    public $property = 'test';
}

class Container
{
    public function getItem()
    {
        return new Item();
    }
}

echo get_class(($object = (new Container())->getItem())); // returns Item

// this comes up with error
echo ($object = (new Container())->getItem())->property;

为什么最后一行代码会触发PHP Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)

编辑:

看起来我需要澄清我的问题,因为我看到答案与我的问题完全无关。我不是在问如何摆脱语法错误。我的问题是: 为什么我无法访问表达式($object = (new Container())->getItem())上的属性,而get_class()告诉我这是Item的一个实例?

2 个答案:

答案 0 :(得分:6)

你只能在PHP 5.4中取消引用函数返回值(我相信你可以取消引用新创建的数组,如['x','y','z'][$index]

由于赋值不是函数,因此不能取消引用它。

答案 1 :(得分:0)

为什么不使用扩展类?

class Item {
 public $Val = "Testing";

}

class Container extends Item {

    public function getItem()
    {
        return new Item();
    } // This method is no longer needed

}


$Object = new Container();
echo $Object->Val; // Output of: Testing

自PHP4以来已经可以使用

Manual For Extends

或者如果您希望从OOP Scope初始化对象:

Class Item { 
 public $Val = "SomeString"; 
}

class Container { 
 public $Instance;
 public function __construct(){
   $this->Instance = new Item();
 } 

}
$Object = new Container();
echo $Object->Instance->Val;