关于PHP神奇方法的问题&;授权
我想用另一种方式来包装一个对象——更倾向于组合而不是继承。但是我不确定我做得对,因为没有错误 我创建了一个类关于PHP神奇方法的问题&;授权,php,Php,我想用另一种方式来包装一个对象——更倾向于组合而不是继承。但是我不确定我做得对,因为没有错误 我创建了一个类Wrapped,它由Wrapper包装。我这样做的目的是,当在$wrapper上调用方法/属性时,如果它存在于类wrapper中,它将返回给else,它将委托给$wrapped对象。我想知道除了我没有检查方法/属性是否存在之外,我做错了什么?有人能解释一下\u callStatic()吗 class Wrapped { protected $wrappedProp1 = 'Wrap
Wrapped
,它由Wrapper
包装。我这样做的目的是,当在$wrapper
上调用方法/属性时,如果它存在于类wrapper
中,它将返回给else,它将委托给$wrapped
对象。我想知道除了我没有检查方法/属性是否存在之外,我做错了什么?有人能解释一下\u 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();
看起来,一切都很好 关于_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 );"