在所有类实例上调用方法

时间:2013-11-12 10:01:37

标签: php oop

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

示例:

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

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

1 个答案:

答案 0 :(得分:1)

可以这样做:

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