How to build multi oop functions in PHP5

对着背影说爱祢 提交于 2019-11-28 11:45:24

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.

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

This isn't strictly valid PHP, but what this is saying is... You are calling a method on the $object class that itself returns an object in which you are calling a method called first() which also returns an object in which you are calling a method called second().

So, this isn't necessarily just one class (although it could be) with one method, this is a whole series of possibly different classes.

Something like:

class AnotherClass {
    public function AnotherClassMethod() {
        return 'Hello World';
    }
}

class MyClass {
    public function MyClassMethod() {
        return new AnotherClass();
    }
}

$object = new MyClass();
echo $object->MyClassMethod()->AnotherClassMethod();  // Hello World
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!