如何从扩展的 PHP 类中的静态调用中获取类名? [英] How can I get the classname from a static call in an extended PHP class?

查看:31
本文介绍了如何从扩展的 PHP 类中的静态调用中获取类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类:ActionMyAction.后者声明为:

I have two classes: Action and MyAction. The latter is declared as:

class MyAction extends Action {/* some methods here */}

我只需要Action类中的方法(只在里面,因为会有很多继承的类,我不想在所有的类中都实现这个方法),这将从静态调用返回类名.这就是我要说的:

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__ 变量,其值为Action".

But each declaration in the parent class has access only to the parent class __CLASS__ variable, which has the value "Action".

有没有办法做到这一点?

Is there any possible way to do this?

推荐答案

__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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆