rpbramos
rpbramos

Reputation: 21

How to pass a chained method as an argument for another method in the same class?

I have a class with a bunch of chained methods. Here is an example:

class Sum {
    public static $res = [];
    private static $instance = null;

    public static function run() {
        if (self::$instance === null)
            self::$instance = new self;

        return self::$instance;
    }

    public function res() {
        return self::$res;
    }

    public function addTen($int) {
        self::$res = $this->addFour($str) + 6;
        return $this;
    }

    public function addFour($int) {
        self::$res = $int + 4;
        return $this;
    }
}

So if I want to call the addTen() method I can do like so:

echo Sum::run()->addFour(5)->res(); // Works, returns 9
echo Sum::run()->addTen(5)->res(); // Doesn't work

The above code doesn't work because the chained methods return the current object from the Sum class. So I managed to fix this by changing the addTen() method so it calls the res() method after the addFour() method like so:

public function addTen($int) {
    self::$res = $this->addFour($str)->res() + 6;
    return $this;
}

In the above case, that is ok because there is only on method being called from inside the addTen() method but what if I need to call a lot of other chained methods from inside the addTen() method? How can I do so the res() method is no longer needed to be called after every single call from another chained method inside the class (it could become unhandable to have a lot of "->res()" being called everywhere in the class).

Upvotes: 2

Views: 183

Answers (1)

azngunit81
azngunit81

Reputation: 1604

I do not know what is your task for this class, but manually writing "add" per function will not make your class adaptable. As I have noted, you have used an array and not chain the $res properly. Since this is a sum class I would expect that you want to sum up the chain.

so I rewrote your class:

<?php

class Sum {
    public static $res = [];
    private static $instance = null;

    public static function run() {
        if (self::$instance === null)
            self::$instance = new self;

        return self::$instance;
    }

    public function res() {
        return array_sum(self::$res);
    }

    public function add($int) {
        self::$res[] = $int;
        return $this;
    }

}
$sum = new Sum();
$x = $sum->add(5)->add(6)->res();
echo $x; // 11

and you can see it work here: https://3v4l.org/itDHN

Upvotes: 1

Related Questions