【问题标题】:PHP Class LogicPHP 类逻辑
【发布时间】:2010-09-24 00:18:19
【问题描述】:

我的问题很简单,因为:

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

$c=new MyClass;
$c->a()->b()->b()->a();

这样它就会输出:

F.A F.B F.B F.A

需要对代码进行哪些更改才能使其正常工作,或者它应该按原样工作,甚至只是所谓的。如果我能得到这个术语的名称,我可以研究它 mysqlf,但我不太确定 Google 是什么。

提前致谢!

【问题讨论】:

    标签: php oop class abstract-class


    【解决方案1】:

    在每个函数中你必须:

      return $this;
    

    【讨论】:

    • Returnin $this 可以让你进行对象线的连锁效应,+1 不妨接受这个答案。
    • 谢谢你们!这正是我想要的!
    【解决方案2】:

    将这样的方法串在一起称为“链接”。

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

    你必须明确地这样做,因为PHP functions will return NULL by default

    所以,你只需要多 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();
    ?>
    

    Live Example

    查看 this article by 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 )
    ?>
    

    Live Example

    【讨论】:

    • 谢谢你们!这正是我想要的!
    【解决方案3】:

    方法链接在特定领域的语言中被大量使用,特别是由 Martin Fowler 创造的所谓的“流畅接口”。如果您想探索这种富有表现力的编程风格,请参阅他的 DSL 书籍在线预印本。 http://martinfowler.com/dslwip/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 2013-01-20
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多