PHP类逻辑

Add*_*ons 1 php oop abstract-class class

我的问题很简单,给出:

class MyClass{
   function a(){
       echo "F.A ";
   }
   function b(){
       echo "F.B ";
   }
}

$c=new MyClass;
$c->a()->b()->b()->a();
Run Code Online (Sandbox Code Playgroud)

所以它会输出:

FA FB FB FA

需要对代码进行哪些更改才能使其工作,或者它应该按原样工作,甚至只是调用它.如果我可以得到任何这个术语,我可以研究它mysqlf,但我不太确定谷歌是什么.

提前致谢!

col*_*ium 7

在每个功能中,您必须:

  return $this;
Run Code Online (Sandbox Code Playgroud)


Pet*_*tai 6

将类似的方法串在一起称为"链接".

return $this; 在每个方法中都将启用可链接性,因为它不断地将实例从一个方法传递到另一个方法,从而维护链.

您必须明确地执行此操作,因为PHP函数将NULL默认返回.

所以,你只需要2行.

<?php
    class MyClass{
   function a(){
       echo "F.A ";
       return $this; // <== Allows chainability
   }
   function b(){
       echo "F.B ";
       return $this;
   }
}

$c=new MyClass;
$c->a()->b()->b()->a();
?>
Run Code Online (Sandbox Code Playgroud)

实例

请看John Squibb撰写的这篇文章,以进一步探索PHP中的可链接性.


你可以做各种具有可链接性的东西.方法通常涉及参数.这是一个"论证链":

<?php
   class MyClass{
   private $args = array();
   public function a(){
       $this->args = array_merge($this->args, func_get_args());
       return $this;
   }
   public function b(){
       $this->args = array_merge($this->args, func_get_args());
       return $this;
   }
   public function c(){
       $this->args = array_merge($this->args, func_get_args());
       echo "<pre>";
       print_r($this->args);
       echo "</pre>";       
       return $this;
   }   
}

$c=new MyClass;
$c->a("a")->b("b","c")->b(4, "cat")->a("dog", 5)->c("end")->b("no")->c("ok");

// Output:
//   Array ( [0] => a [1] => b [2] => c [3] => 4 [4] => cat 
//           [5] => dog [6] => 5 [7] => end )
//   Array ( [0] => a [1] => b [2] => c [3] => 4 [4] => cat 
//           [5] => dog [6] => 5 [7] => end [8] => no [9] => ok )
?>
Run Code Online (Sandbox Code Playgroud)

实例