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.
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()
.