典型的使用方法:
<?php
class A {
public $var;
public function __construct($var){
$this->var = $var;
}
public function do_print(){
print $this->var;
}
}
?>
$obj = new A('Test');
$obj->do_print(); // Test
Run Code Online (Sandbox Code Playgroud)
我该如何实现以下内容:
$obj->var->method();
Run Code Online (Sandbox Code Playgroud)
为什么这有用?
通过创建var另一个类的对象,您可以将方法调用链接到另一个类.
<?php
class Foo {
public $bar;
public function __construct(Bar $bar) {
$this->bar= $bar;
}
}
class Bar {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function printName() {
echo $this->name;
}
}
$bar = new Bar('Bar');
$bar2 = new Bar('Bar2');
$foo = new Foo($bar);
$foo->bar->printName(); // Will print 'Bar';
$bar2->printName(); // Will print 'Bar2'
Run Code Online (Sandbox Code Playgroud)
您可以将它用于依赖注入等整洁的东西
此外,它可能使您的代码更易于阅读和理解,因为您不必在调用其方法之前缓冲变量,而只能在另一个之后调用一个方法.
看看这个例子:
$obj = new MyObject();
$db = $obj->getDb();
$con = $db->getCon();
$stat = $con->getStat();
Run Code Online (Sandbox Code Playgroud)
使用方法链接可以这样编写:
$obj = new Object();
$stat = $obj->getDB()->getCon()->getStat();
Run Code Online (Sandbox Code Playgroud)
但是,这也很难调试,因为如果这些方法中的任何一个抛出异常,你只需得到链所在的行号,这可能是一个很大的问题.
所以,总有两面.这只是另一种编程风格.
确保不要在一行中链接太长时间,因为你肯定会失去概述.
坏
$obj->meth('1', $arg2, array('arg2'))->method2($whaterver, array('text' => $bla_text))->andSoOn();
Run Code Online (Sandbox Code Playgroud)
好
$obj->meth('1', $arg2, array('arg2'))
->method2($whaterver, array('text' => $bla_text))
->andSoOn();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
636 次 |
| 最近记录: |