drzyeetvt41077335
2009-02-03 11:04
浏览 69
已采纳

如何从扩展PHP类中的静态调用中获取类名?

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

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

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 */}
}

And when I call it:

MyAction::n(); // it should return "MyAction"

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?

图片转代码服务由CSDN问答提供 功能建议

我有两个类: Action MyAction 。 后者声明为:

  class MyAction扩展Action {/ *这里的一些方法* /} 
   
 
 

我需要的只是 Action 类中的方法(仅在其中,因为会有很多继承的类,我不想在所有这些中实现此方法),这将返回 静态调用的classname。 以下是我所说的:

  Class Action {
 function n(){/ * something * /} 
} 
   
 
 

当我调用它时:

  MyAction :: n();  //它应该返回“MyAction”
   
 
 

但是父类中的每个声明只能访问父类 __ CLASS __ 变量, 具有值“Action”。

有没有可行的方法呢?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

6条回答 默认 最新

  • dongzha5934 2009-02-03 11:16
    最佳回答

    __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'
    

    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.

    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
    
    评论
    解决 无用
    打赏 举报
查看更多回答(5条)

相关推荐 更多相似问题