Dakota K
Dakota K

Reputation: 141

Calling method on all instances of class

I am looking for a way to call a function on all instances of a class preferably via a static method call.

Example:

class number{

    private $number;

    static function addAll(){
        //add all of the values from each instance together
    }

    function __construct($number){
        $this->number = $number;
    }
}

$one = new number(1);
$five = new number(5);

//Expecting $sum to be 6
$sum = number::addAll();

Any help on this would be greatly appreciated. Thanks!

Upvotes: 0

Views: 145

Answers (1)

hek2mgl
hek2mgl

Reputation: 157992

It can be done like this:

class MyClass {

    protected $number;

    protected static $instances = array();

    public function __construct($number) {
        // store a reference of every created object
        static::$instances [spl_object_hash($this)]= $this;
        $this->number = $number;
    }


    public function __destruct() {
        // don't forget to remove objects if they are destructed
        unset(static::$instances [spl_object_hash($this)]);
    }


    /**
     * Returns the number. Not necessary here, just because
     * you asked for an object method call in the headline
     * question.
     */
    public function number() {
        return $this->number;
    }


    /**
     * Get's the sum from all instances
     */
    public static function sumAll() {
        $sum = 0;
        // call function for each instance
        foreach(static::$instances as $hash => $i) {
            $sum += $i->number();
        }
        return $sum;
    }
}

Upvotes: 1

Related Questions