Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OOP: Method Chaining

I have the following code,

<?php
class Templater
{
    static $params = array();

    public static function assign($name, $value)
    {
        self::$params[] = array($name => $value);
    }

    public static function draw()
    {
        self::$params;
    }
}


 $test = Templater::assign('key', 'value');
 $test = Templater::draw();
 print_r($test);

How can I alter this script so I could use this?

$test = Templater::assign('key', 'value')->assign('key2', 'value2')->draw();
print_r($test);
like image 641
Isis Avatar asked Dec 04 '22 12:12

Isis


2 Answers

You cannot use Method Chaining with static methods because you cannot return a class level scope (return self won't do). Change your methods to regular methods and return $this in each method you want to allow chaining from.

Notice that you should not use T_PAAMAYIM_NEKUDOTAYIM to access instance methods as it will raise an E_STRICT Notice. Use T_OBJECT_OPERATOR for calling instance methods.

Also see:

  • Chaining Static Methods in PHP?
like image 158
Gordon Avatar answered Dec 16 '22 14:12

Gordon


You shouldn't be using static members:

class Templater
{
    private array $params = [];

    public function assign($name, $value) : self
    {
        $this->params[$name] = $value;

        return $this;
    }

    public function draw()
    {
        // do something with $this->params
    }
}

$test = (new Templater())->assign('key', 'value')->assign('key2', 'value2')->draw();
like image 23
Artefacto Avatar answered Dec 16 '22 13:12

Artefacto