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 に答える