0

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

例子:

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

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

4

1 回答 1

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;
    }
}
于 2013-11-12T10:09:51.683 回答