我对 PHP 中的“静态”和“动态”函数和对象如何协同工作感到困惑,特别是在 __callStatic() 方面。
How __callStatic() works:
You can have a normal class MyClass, where within the class you can put a static function called __callStatic(), which gets called only when MyClass doesn't have a static function by the name you want.
i.e. I call
MyClass::newFunction();
newFunction()
is called statically butMyClass
does not have it declared. So, then__callStatic()
gets called and inside you can say$myObject=new SomeOtherClass(); $myObject->newFunction();
which calls the function you wanted but on some other object.
简短版本:
换句话说,__callStatic() 执行以下操作:
MyClass::newFunction();
它隐藏了这个:
(new SomeOtherClass())->newFunction();
现在说什么?看起来像是从类中调用静态函数的代码,结果是从其他类中调用该函数并通过实例化而不是静态地调用它。
请解释一下!
为什么这样做?你能在其他地方做类似的事情吗,比如 C++ 或 Java?我正在寻找关于语言中静态和动态函数的简短但信息丰富的解释,以及在这种情况下 __callStatic() 违反
还是符合
语言的大局结构体。或者它完全是一种新的语言构造。
最佳答案
__callStatic()
为开发人员提供了对 static
方法调用使用react的可能性,即使该方法不存在或不可访问来自类外部(受保护
)。这对于动态、通用代码生成很有用。
示例:您有此类:
class Test {
protected static function myProtected($test) {
var_dump(__METHOD__, $test);
}
public static function __callStatic($method, $args) {
switch($method) {
case 'foo' :
echo 'You have called foo()';
var_dump($args);
break;
case 'helloWorld':
echo 'Hello ' . $args[0];
break;
case 'myProtected':
return call_user_func_array(
array(get_called_class(), 'myProtected'),
$args
);
break;
}
}
}
尝试调用:
// these ones does not *really* exist
Test::foo('bar');
Test::helloWorld('hek2mgl');
// this one wouldn't be accessible
Test::myProtected('foo');
关于php - __callStatic() : instantiating objects from static context?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840911/