将PHP类作为参数传递?

时间:2017-09-29 03:19:32

标签: php

如何将当前类作为参数传递? 例如:

class Example 
{
    public function test() {
        $class = new Class2(I want to pass the Example class instance here)
    }
}

class Class2 
{
    public function __construct(Example $example) {
    }
}

3 个答案:

答案 0 :(得分:0)

class Example 
{
    public function test() {
        $class = new Class2(new static());
    }
}

答案 1 :(得分:0)

你可以把它传递给$ this,new self()或new static()。你会得到同样的结果。

class Example 
{
    public $name = "test";

    public function test() {
        return $class = new Class2($this);
    }
}

class Class2 
{
    private $example = null;
    public function __construct(Example $example) {
        $this->example = $example;
    }

    public function testMe() {
        echo $this->example->name;
    }

    public function setExampleName($name) {
        $this->example->name = $name;
    }
}

$e = new Example();

$e->test()->testMe();

结果:

test

答案 2 :(得分:0)

在对象创建期间将$ this作为参数发送。因为$ this代表当前的类对象,这里的例子是

{{1}}