How to execute several methods of a class in the same PHP line [duplicated]

1

Hi, I wanted to know what structure the class should have so that once instantiated, several methods can be executed in a single line, for example I saw in several CMS or projects this:

$NombreClase = new NombreClase();
$NombreClase->crearTexto('algo')->convertirAMatusculas()->hacerOtraCosa();

This, how is it done? What structure does the class have to have or what properties must each method have?

Greetings

    
asked by Chiiviito 02.08.2017 в 20:40
source

2 answers

6

The idea would be to create an instance method. Look at this example, it fulfills what you proposed.

Always keep in mind what functions return.

class NombreClase {

    private $algo;

    public function crearTexto($algo) {
        $this->algo=$algo;
        return $this;
    }

    public function convertirAMayusculas() {
        $this->algo=strtolower($this->algo);
        return $this;
    }

    public function hacerOtraCosa(){
        return $this;
    }
}

$NombreClase = new NombreClase();
$NombreClase->crearTexto('algo')->convertirAMayusculas()->hacerOtraCosa();

This should work.

Salu2 .-

    
answered by 02.08.2017 в 21:21
2

All your methods in the class $NombreClase must end with return $this;

    
answered by 02.08.2017 в 20:57