Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a question about OOP in PHP5. I have seen more and more code written like this:

$object->function()->first(array('str','str','str'))->second(array(1,2,3,4,5));

But I don't know how to create this method. I hope somebody can help me here, :0) thanks a lot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

The key to chaining methods like that within your own classes is to return an object (almost always $this), which then gets used as the object for the next method call.

Like so:

class example
{
    public function a_function()
    {
         return $this;
    }

    public function first($some_array)
    {
         // do some stuff with $some_array, then...
         return $this;
    }
    public function second($some_other_array)
    {
         // do some stuff
         return $this;
    }
}

$obj = new example();
$obj->a_function()->first(array('str', 'str', 'str'))->second(array(1, 2, 3, 4, 5));

Note, it's possible to return an object other than $this, and the chaining stuff above is really just a shorter way to say $a = $obj->first(...); $b = $a->second(...);, minus the ugliness of setting variables you'll never use again after the call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...