关于PHP Magic Methods&的问题委派

时间:2010-08-03 06:30:22

标签: php

我想把一个对象包装在另一个 - 有利于组合而不是继承。但我不确定我做得对,没有错误。

我创建了一个由Wrapped包裹的类Wrapper。我这样做,当在$wrapper上调用方法/属性时,如果它存在于类Wrapper中,它将被返回,否则它将委托给$wrapped对象。我想知道除了我没有检查方法/属性是否存在的事实,我做错了什么?有人可以解释__callStatic()吗?

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

1 个答案:

答案 0 :(得分:1)

看起来 - 一切都好。

关于__callStatic() - 它允许您在类中解决未定义的静态函数。 例如:

<?php
class Foo {
    static function __callStatic($name, $args = array()) {
        echo "Called static function $name with arguments ". print_r($args, true);
    }
}

Foo::Bar('test');
// will output "Called static function Bar with arguments Array ( 0 => test );"