sam*_*ayo 2 php oop method-chaining
假设我有这门课.
class foo{
function a(){
return $this;
}
}
Run Code Online (Sandbox Code Playgroud)
.
$O = new foo();
$O->a()
->a()
->a();
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以知道,在最后一个函数->a()
之前它被调用了多少次?因此,我可以像'method ->a() has been called twice before this.'
我想要找到的那样输出,不使用增量值,如声明属性,然后递增增加它,每次在函数中调用它.
如果OOP中有一个可以提供此解决方案的隐藏功能,我只是跳来跳去
您可以在方法内使用静态变量:
class foo{
function a(){
// $count will be initialized the first time a() was called
static $count = 0;
// counter will be incremented each time the method gets called
$count ++;
echo __METHOD__ . " was called $count times\n";
return $this;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,static
在方法或函数中使用它时具有不同的含义,它与静态类成员无关 - 尽管它是相同的关键字.这意味着只有在第一次调用方法时,才会创建和初始化变量一次.
但是,在上面的示例中,无法重新初始化该计数器.如果你想这样做,你可能会引入一个参数或类似的东西.你也可以不使用static
变量而是使用对象属性.有数以千计的方法可以做到,请告诉我你的具体应用需求我可能会给出一个更具体的例子....
在评论中,建议使用装饰器来完成这项工作.我喜欢这个想法,并举一个简单的例子:
class FooDecorator
{
protected $foo;
protected $numberOfCalls;
public function __construct($foo) {
$this->foo = $foo;
$this->reset();
}
public function a() {
$this->numberOfCalls++;
$this->foo->a();
return $this;
}
public function resetCounter() {
$this->numberOfCalls = 0;
}
public function getNumberOfCalls() {
return $this->numberOfCalls;
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
$foo = new FooDecorator(new foo());
$foo->a()
->a()
->a();
echo "a() was called " . $foo->getNumberOfCalls() . " times\n";
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2492 次 |
最近记录: |