简体   繁体   English

PHP OOP CLASS链接

[英]PHP OOP CLASS chaining

I have seen people do this: 我见过人们这样做:

$controller->bar->stuff->foo();

I suppose this is CLASS chaining? 我想这是CLASS链接吗?

How is this achievable? 这是如何实现的? (if at all achievable) (如果完全可以实现)

NOTE. 注意。 I am not asking about method chaining. 我不是在问方法链接。

Cheers! 干杯!

EDIT: Forgot to ask this... how would this benefit me? 编辑:忘记问这个...这将如何使我受益? If you guys could write a short example it'd be great! 如果你们能写一个简短的例子,那就太好了!

This is achieved via accessible properties. 这是通过可访问的属性实现的。 For example, using public properties... 例如,使用public属性...

class Stuff {
    public function foo() {}
}

class Bar {
    /**
     * @var Stuff
     */
    public $stuff;

    public function ___construct(Stuff $stuff) {
        $this->stuff = $stuff;
    }
}

class Controller {
    /**
     * @var Bar
     */
    public $bar;

    public function __construct(Bar $bar) {
        $this->bar = $bar;
    }
}

$stuff = new Stuff();
$bar = new Bar($stuff);
$controller = new Controller($bar);

$controller->bar->stuff->foo();

I wouldn't recommend this as it leaves your classes open to external modification. 我不建议这样做,因为它会使您的类易于进行外部修改。 Another method might be via magic getter methods, for example 例如,另一种方法可能是通过魔术吸气剂方法

class Controller {
    private $properties = [];

    public function __construct(Bar $bar) {
        $this->properties['bar'] = $bar;
    }

    public function __get($name) {
        return array_key_exists($name, $this->properties)
            ? $this->properties[$name] : null;
    }
}

This means you can still access the property in the private $properties array like it was a public property (eg $controller->bar ) without it being open to external modification. 这意味着您仍然可以访问私有$properties数组中的$properties就像它是公共属性一样(例如$controller->bar ),而无需对其进行外部修改。

In my opinion though, keep properties private / protected and provide accessor methods 不过,我认为,将属性设为私有/受保护并提供访问器方法

class Controller {
    /**
     * @var Bar
     */
    private $bar;

    public function __construct(Bar $bar) {
        $this->bar = $bar;
    }

    /**
     * @return Bar
     */
    public function getBar() { return $this->bar; }
}

$controller->getBar()->someBarMethod()->etc();

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

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