__ Get () ve __ seti () ile özel / kamu özelliklerini taklit?

0 Cevap php

Ben __ get () ve __ set (), bir ana dizideki dizi öğelerini depolamak ve almak için kullandığı bir sınıf yazıyordu. Ben temelde özel özelliklerini yeniden oluşturmak için, bazı unsurlar Çıkarılamayanları yapmak için bir onay vardı.

Ben o görünüyordu fark __ sınıf özelliklerine yakaladığını tüm aramaları olsun. Ben (GET yoluyla kullanılamaz) dış dünyaya bir değişken Private istedim çünkü bu, benim için berbat, ama ben doğrudan sınıf içinde ana diziyi başvurarak erişmeye çalışıyordu. Tabii ki, ana dizi gettable özelliklerinin Beyaz liste değildir: (

Ben __ get () ve __ set () kullanan bir php sınıfta kamu ve özel özelliklerini taklit bir yolu var mı?

Örnek:

<?

abstract class abstraction {

    private $arrSettables;
    private $arrGettables;
    private $arrPropertyValues;
    private $arrProperties;

    private $blnExists = FALSE;

    public function __construct( $arrPropertyValues, $arrSettables, $arrGettables ) {

        $this->arrProperties = array_keys($arrPropertyValues);
        $this->arrPropertyValues = $arrPropertyValues;
        $this->arrSettables = $arrSettables;
        $this->arrGettables = $arrGettables;
    }

    public function __get( $var ) {
        echo "__get()ing:\n";
        if ( ! in_array($var, $this->arrGettables) ) {
            throw new Exception("$var is not accessible.");
        }

        return $this->arrPropertyValues[$var];
    }

    public function __set( $val, $var ) {
        echo "__set()ing:\n";
        if ( ! in_array($this->arrSettables, $var) ) {
            throw new Exception("$var is not settable.");
        }

        return $this->arrPropertyValues[$var];
    }

} // end class declaration

class concrete extends abstraction {

    public function __construct( $arrPropertyValues, $arrSettables, $arrGettables ) {
        parent::__construct( $arrPropertyValues, $arrSettables, $arrGettables );
    }

    public function runTest() {

        echo "Accessing array directly:\n";
        $this->arrPropertyValues['color'] = "red";
        echo "Color is {$this->arrPropertyValues['color']}.\n";

        echo "Referencing property:\n";
        echo "Color is {$this->color}.\n";
        $this->color = "blue";
        echo "Color is {$this->color}.\n";

        $rand = "a" . mt_rand(0,10000000);
        $this->$rand = "Here is a random value";
        echo "'$rand' is {$this->$rand}.\n";

    }
}

try {
    $objBlock = & new concrete( array("color"=>"green"), array("color"),  array("color") );
    $objBlock->runTest();
} catch ( exception $e ) {
    echo "Caught Exeption $e./n/n";
}

// no terminating delimiter

$ php test.php
Accessing array directly:
__get()ing:
Caught Exeption exception 'Exception' with message 'arrPropertyValues is not accessible.' in /var/www/test.php:23
Stack trace:
#0 /var/www/test.php(50): abstraction->__get('arrPropertyValu...')
#1 /var/www//test.php(68): concrete->runTest()
#2 {main}.

0 Cevap