在类的所有实例上调用方法


Calling method on all instances of class

我正在寻找一种在类的所有实例上调用函数的方法,最好是通过静态方法调用。

例:

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();

对此的任何帮助将不胜感激。谢谢!

可以这样完成:

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;
    }
}