简体   繁体   English

如何在PHP中创建嵌套方法?

[英]How do you create nested methods in PHP?

For example, I've seen third-party applications that have functions like this: 例如,我见过具有以下功能的第三方应用程序:

$db->select('columns')->from('table')->where('condition');

That's just an example. 这只是一个例子。 How do you create methods like that? 您如何创建类似的方法?

To accomplish this, each of the methods should return $this , an instance of the class which contains the methods. 为此,每个方法都应返回$this ,它是包含方法的类的实例。

class MyClass {

   public function select($x){
      // do something
      return $this;
   }

   public function from($x){
      // do something
      return $this;
   }

   public function where($x){
      // do something
      return $this;
   }

}

inside these methods, you generally perform some kind of modification to the state of the object. 在这些方法中,通常可以对对象的状态进行某种修改。

In your example, the methods are simply returning objects. 在您的示例中,方法只是返回对象。 So $db->select() returns an object with a method from() , which returns an object with a method where() . 因此$db->select()返回一个带有from()方法的对象,而from()返回一个带有where()方法的对象。

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

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