简体   繁体   English

通过PHP类作为参数?

[英]Passing PHP class as parameter?

How can I pass the current class as a parameter? 如何传递当前类作为参数? Example: 例:

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

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

you can pass it as $this, new self() or new static(). 您可以将其作为$ this,new self()或new static()传递。 and you will get the same result. 您将获得相同的结果。

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();

the result: 结果:

test

send $this in as the parameter during object creation. 在对象创建过程中发送$ this作为参数。 Because $this represent the current class object Which Example here 因为$ this代表当前的类对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM