__callStatic():从静态上下文实例化对象吗? [英] __callStatic(): instantiating objects from static context?
问题描述
我对PHP中的静态"和动态"函数与对象如何协同工作感到困惑,尤其是在__callStatic()方面.
I am confused about how "static" and "dynamic" functions and objects in PHP work together especially with regards to __callStatic().
__callStatic()的工作方式:
您可以有一个普通的类MyClass,在该类中您可以 放置一个名为__callStatic()的静态函数,该函数仅被调用 当MyClass没有想要的名称的静态函数时.
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.
即我叫MyClass::newFunction();
newFunction()
被静态调用,但MyClass
不被静态调用
宣布.因此,然后__callStatic()
被调用并
在里面你可以说
newFunction()
is called statically but MyClass
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()做到了:
In other words, __callStatic() does this:
MyClass::newFunction();
其中隐藏了这个内容:
(new SomeOtherClass())->newFunction();
现在说些什么?看起来像代码从类中调用静态函数的代码,原来是从其他某个类中调用该函数,并通过实例化而不是静态地调用它.
Say what now? What looks like code calling a static function from a class, turns out to be calling that function from some other class and calling it via instantiation, and not statically.
请解释一下!
为什么要做?您可以在其他地方(例如C ++或Java)做类似的事情吗?我正在寻找短&对语言中的静态和动态函数的简要而有启发性的解释,在这种情况下,是对__语言构造的总体了解还是__callStatic()violates
或conforms
.还是完全是一种新的语言结构.
Why was it done? Can you do anything like this elsewhere, like C++ or Java? I am looking for short & concise, but informative explanation on static and dynamic functions in languages, and in this case whether __callStatic() violates
or conforms
to the big picture of Language constructs. Or is it a new language construct entirely.
推荐答案
__callStatic()
为开发人员提供了对static
方法调用做出反应的可能性,即使该方法不存在或从类外部(protected
)可以访问.这对于动态的通用代码生成很有用.
__callStatic()
provides developers with possibility to react on static
method calls even if that methods don't exist or aren't accessible from outside of the class ( being protected
). This is useful for dynamic, generic code generation.
示例:您拥有此类:
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');
这篇关于__callStatic():从静态上下文实例化对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!