PHP Sihirli Yöntemler ve abt Sorular

0 Cevap

i başka bir nesneyi kaydırmak isteyen oldu - miras üzerinden kompozisyon lehine. ama ben hiçbir hata vardır sağ tho yapıyorum emin değilim.

i bir sınıf Wrapped şu Wrapper tarafından sarılır yarattı. ben böyle bir yöntem / özellik bu sınıfta varsa $wrapper, Wrapper, Başka iade edilecektir çağrıldığında, o ({[devredebilir edeceğini yaptı 4)]} nesne. i yöntem / özellik yanlış, ben ne yaptım varsa ben onay vermedi aslında dışında acaba? Some1 çok __callStatic() açıklayabilir?

class Wrapped {
    protected $wrappedProp1 = 'Wrapped: Property 1';
    protected $wrappedProp2 = 'Wrapped: Property 2';

    function method1($arg1, $arg2) {
        echo "Called Wrapped::method1() with the following parameters: $arg1, $arg2";
    }

    static function sMethod2() {
        echo 'Called a static method in wrapped';
    }

    function __get($name) {
        return $this->$name;
    }
    function __set($name, $val) {
        $this->$name = $val;
    }
}
class Wrapper {
    protected $wrapperProp1 = 'Wrapper: Property 1';
    protected $wrapped;

    function __construct($wrapped) {
        $this->wrapped = $wrapped;
    }

    function wrapperMethod() {
        echo 'In wrapper method';
    }

    function __get($name) {
        if (property_exists($this, $name)) {
            return $this->$name;
        }
        return $this->wrapped->$name;
    }
    function __set($name, $val) {
        if (property_exists($this, $name)) {
            $this->$name = $val;
        }
        $this->wrapped->$name = $val;
    }
    function __call($name, $args = array()) {
        call_user_func_array(array($this->wrapped, $name), $args);
    }
    static function __callStatic($name, $args = array()) {
        call_user_func_array(array('Wrapped', $name), $args);
    }
}

$wrapper = new Wrapper(new Wrapped);

// testing normal methods
$wrapper->wrapperMethod();
echo $wrapper->wrapperProp1;
$wrapper->wrapperProp1 = 'New Wrapper Prop 1';
echo $wrapper->wrapperProp1;

// testing delegates
$wrapper->method1('hello', 'world'); //delegated to Wrapped::method1()
$wrapper->sMethod2(); // delegated to static Wrapped::sMethod2() ... what is callStatic for then
echo $wrapper->wrappedProp2;
Wrapper::sMethod2();

0 Cevap