如何从扩展PHP类中的静态调用中获取类名? [英] How can I get the classname from a static call in an extended PHP class?
问题描述
我有两个类: Action
和 MyAction
。后者被声明为:
I have two classes: Action
and MyAction
. The latter is declared as:
class MyAction extends Action {/* some methods here */}
我需要的只是 Action
类中的方法(仅在其中,因为将有很多继承的类,我不想在所有这些中实现这个方法),它将从静态调用返回classname。以下是我所说的:
All I need is method in the Action
class (only in it, because there will be a lot of inherited classes, and I don’t want to implement this method in all of them), which will return classname from a static call. Here is what I’m talking about:
Class Action {
function n(){/* something */}
}
当我给它打电话时:
MyAction::n(); // it should return "MyAction"
但是父类中的每个声明只能访问父类class __ CLASS __
变量,其值为Action。
But each declaration in the parent class has access only to the parent class __CLASS__
variable, which has the value "Action".
有没有可行的方法呢?
推荐答案
__ CLASS __
始终返回使用它的类的名称,所以它对静态方法没有多大帮助。如果方法不是静态的,您只需使用 get_class ($ this)。例如。
__CLASS__
always returns the name of the class in which it was used, so it's not much help with a static method. If the method wasn't static you could simply use get_class($this). e.g.
class Action {
public function n(){
echo get_class($this);
}
}
class MyAction extends Action {
}
$foo=new MyAction;
$foo->n(); //displays 'MyAction'
后期静态绑定,PHP 5.3 +
现在发布了PHP 5.3,你可以使用后期静态绑定,它允许您在运行时而不是在定义时解析静态方法调用的目标类。
Late static bindings, available in PHP 5.3+
Now that PHP 5.3 is released, you can use late static bindings, which let you resolve the target class for a static method call at runtime rather than when it is defined.
虽然该功能未引入新的魔术常量告诉你通过它调用的类名,它确实提供了一个新功能, get_called_class()可以告诉你调用静态方法的类的名称。这是一个例子:
While the feature does not introduce a new magic constant to tell you the classname you were called through, it does provide a new function, get_called_class() which can tell you the name of the class a static method was called in. Here's an example:
Class Action {
public static function n() {
return get_called_class();
}
}
class MyAction extends Action {
}
echo MyAction::n(); //displays MyAction
这篇关于如何从扩展PHP类中的静态调用中获取类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!