Home > Backend Development > PHP Tutorial > 关于php构造函数的疑问

关于php构造函数的疑问

WBOY
Release: 2016-06-06 20:15:29
Original
885 people have browsed it

<code>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(); //正常</code>
Copy after login
Copy after login

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

回复内容:

<code>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(); //正常</code>
Copy after login
Copy after login

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

php什么版本呀?

<code>(new Test($obj))->client</code>
Copy after login

这种表达式5.4以前不支持

<code>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();
</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template