How to do a PHP nested class or nested methods?
The standard convention for this is to return the instance of $this at the end of each of the method call. So when returned to the caller we are then just referencing another method call.
class Foo
{
public function do_something()
{
return $this;
}
public function do_something_else()
{
return $this;
}
}
$foo = new Foo();
$foo->do_something()->do_something_else();
Have the methods return objects with the methods described, and you get what you are after.
So, as long as $DB
is an object that has a comments()
-method, that part is valid. If that comments()
returns an object that has an id()
-method, that part is valid, too. Then, id()
needs to return an object that has the limit()
-method.
In your particular case, you might want to do something like this:
class DB {
public function comments() {
// do preparations that make the object select the "comments"-table...
return $this;
}
public function id($string) {
// handle this too...
return $this;
}
public function limit($int) {
// also this
return $this;
}
public function execute() {
$success = try_to_execute_accumulated_db_commands();
return $success;
}
}
$DB = new DB();
$DB->comments()->id(" > 3")->limit(10);
In my example, every method (also not depicted here) would return the object itself, so that commands can be chained together. When the construction of the database query is done, you actually evaluate the query by invoking execute()
that (in my case) would return a boolean that would represent the success of the database execution.
User nickohm suggested that this is called a fluent interface. I must admit that this is a new term for me, but that tells probably more of my knowledge, than the term's usage. ("I just write code, you know...")
Note: $this
is a 'magic' variable that points to the currently active object. As the name suggests, it just returns itself as the return value for the method.