欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

关于php构造函数的疑问

程序员文章站 2023-12-28 09:08:58
...
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不是版本的问题。

回复内容:

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不是版本的问题。

php什么版本呀?

(new Test($obj))->client

这种表达式5.4以前不支持

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();
相关标签: php

上一篇:

下一篇: