PHP OOP Multicall

I saw in some libraries something like this:

$this->getResponse()->setRedirect($returnUrl);

How is this "multiple" executed, or how should a class be built to do something like this?

I think:

class greeting
{
    public function hi()
    {
        public function howAreYou()
        {
            echo 'How are you?';
        }
    }
}
$greet = new greeting;
$greet->hi()->howAreYou();

But I think this is not so good, I would rather use something like extends, but I do not know. Thanks for your suggestions.

+3
source share
5 answers

If it is an instance of a class that calls itself, it is called a "chain of methods."

In PHP can be done with return $this; note that this is a completely different mechanism than class inheritance - in fact, it makes no sense to consider them interchangeable.

See also: https://stackoverflow.com/search?q=method+chaining+php

+4
source

getResponse() , setRedirect().

:

class Foo
{
    public function getResponse()
    {
        $redirect = new Bar();
        return $redirect;
    }
}

class Bar
{
    public function setRedirect($returnUrl)
    {
        // do something
    }
}

$foo = new Foo();

$foo->getResponse()->setRedirect("returnUrl");
+3

.

, , self .

, a >

class greeting
{
    public function hi()
    {
        echo "Hi";

        return $this;
    }

    public function howAreYou()
    {
        echo 'How are you?';

        return $this;
    }
}

$greet = new greeting;
$greet->hi()->howAreYou();

:

$greet->hi()->howAreYou()->hi()->howAreYou();
+2

- , ... ( , , ). , :

Class chainableObject
{
    public $name=null;
    public function __construct($name='')
    {
        $this->name=$name;
        return $this;
    }

    public function setName($name)
    {
        $this->name = $name;
        return $this;//makes chainable
    }

    public function greet()
    {
        echo 'Hello, '.$this->name;
        return $this;
    }
}

$chain = new chainableObject('Frank')->greet();//outputs: Hello, frank

: , , , [create object with name: Frank] = > call method greet . $this, , , ... , : Google php

+1
    class stutter{
      public function a(){
      echo 'h';
      return $this;
     }
      public function b(){
       echo 'hello world!';
     }
    }

$var = new stutter(); > () β†’ ();

:

h hello world

+1

All Articles