PHP - Functions | Instance Methods $ var → func ($ args) → func2 ($ args);

5

I was wondering how I could do this type of functions, or rather how to create a class or what is required to execute the functions in the following way:

$var->metodo1($args)->metodo2($args)->metodo3($args);
  

Under what I assume from the above code, is that the result of method1 is used by method2 and the result of this is used by method3 strong>.

I do not know what that kind of organization is called, that's why I ask the question in this way. I have seen very similar code in Laravel .

I do not know if I'm wrong, that's why I ask. I tried to search Google but found nothing.

    
asked by Máxima Alekz 29.06.2017 в 16:25
source

3 answers

6

The "arrows" refer to an instance method (the functions that an object can invoke when it is instantiated), when applying one after another each method invoked should return an object, with an example it may be understood more:

class Foo() {

    public function devolverNumeroAlCuadrado($num) {
        return $num * $num;
    }

    public function otroMetodo($num) {
        echo "Cualquier cosa";
    }
}

$var= new Foo(); // Instancio el objeto

$var->devolverNumeroAlCuadrado(2)->otroMetodo(); // ERROR! 

Throw error since as devolverNumeroAlCuadrado() returns a number, when calling otroMetodo() we are saying something like this:

4->otroMetodo();

And number 4 does not have that method. Therefore, if we want to call otroMetodo() what the previous methods return will have to be the same instance:

class Foo() {

    public function unMetodo() {
        // Hace algo
        return $this; // Retorna el objeto llamador
    }

    public function otroMetodo($num) {
        echo "Cualquier cosa";
    }
}

$obj1 = new Foo(); // Instancio el objeto

$obj1->unMetodo()->otroMetodo(); // AHORA SI!!! 

Another example using two different classes:

class Foo() {

    public function unMetodo() {
        // Hace algo
        return $this; // Retorna el objeto llamador
    }

    public function otroMetodo($num) {
        return new Bar();
    }
}

class Bar() {
    public function metodoSalvaje() {
        echo "Soy un Bar!";
    }
}

$obj1 = new Foo(); // Instancio el objeto

$obj1->unMetodo()->otroMetodo()->metodoSalvaje();

I hope I have been clear and useful!

Greetings!

    
answered by 29.06.2017 / 16:36
source
2

Just to provide another point of view:

You can also have a class link, which allows you to call the methods in this way:

$prueba->foo()->bar()->fou();

without having to modify the classes foo , bar , fou . In this case, the instance of the test class will be created using the class Encadenador in this way:

$prueba = new Encadenador('Prueba');   

Ejemplo: Ver Demo

<?php 

class Prueba 
{
    function foo(){ echo "FOO\n"; }
    function bar(){ echo "BAR\n"; }
    function fou(){ echo "FOU\n"; }
}



class Encadenador 
{
    private $instance = null;
    public function __construct()
    {
        $pars = func_get_args();
        $this->instance = is_object($obj=array_shift($pars))?$obj:new $obj($pars);
    }

    public function __call($name,$pars)
    {
        call_user_func_array([$this->instance,$name],$pars);
        return $this;
    }

}


$prueba = new Encadenador('Prueba');   
$prueba->foo()->bar()->fou();

?>

Resultado:

FOO
BAR
FOU
    
answered by 29.06.2017 в 18:27
1

How about? It seems to me that what you want to do is chaining methods. This is a fairly used pattern, in which the return of each method in the class you want to chaine, returns the instance of the class. For example:

class miClase {

   public function metodo1($var1) {
      echo "Este es el metodo 1 y recibió ".$var1;      
      return $this; // <-- aca esta la magia

   } 

   public function metodo2($var2) {
      echo "Este es el metodo 2 y recibió ".$var2;
      return $this; // <-- aca esta la magia
   } 
}

Then, you do:

$obj = new miClase();
$obj->metodo1("hola")->metodo2("mundo");

As method 1 devuleve the instance ($ obj), you can chainear automatically with method2. It's as simple as that.

Greetings!

    
answered by 30.06.2017 в 04:49