search

Home  >  Q&A  >  body text

关于php构造函数的疑问

class Test
{
    public $client;
    
    public function __construct($obj)
    {
        $this->client = new Obj(); 
        //    ......
        //  一系列操作
    }
}

// 代码1
$client = (new Test())->client;
$client->method(); //报错

//代码2
$test = new Test();
$client = $test->client;
$cilent->method(); //正常

上述代码出现的原因是什么?php5.6不是版本的问题。

大家讲道理大家讲道理2901 days ago214

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-10 17:02:19

    php什么版本呀?

    (new Test($obj))->client

    这种表达式5.4以前不支持

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 17:02:19

    class Foo {
        public function method(){
            echo 'hi';
        }
    }
    
    class Test {
        public $client;
        public function __construct($obj){
            $this->client = $obj;
        }
    }
    
    $obj = new Foo();
    
    // 代码1
    $client = (new Test($obj))->client;
    $client->method();
    

    reply
    0
  • Cancelreply