duannuci4008 2017-09-01 14:29
浏览 114
已采纳

PHP:动态获取扩展当前类的类的名称[复制]

This question already has an answer here:

I have an abstract class and an extending class:

abstract class MyAbstract {
    public function getName(){echo static::class;}
}

class MyExtends extends MyAbstract {}

I would like to dynamically get the name of any extending class when getName() is called:

$c = new MyExtends();
echo $c->getName(); // expect: "MyExtends"

This works well on PHP 5.6+ (demo), but the project I'm working on is limited to PHP 5.3 and I have no leverage to change that. On that version, a parse error is thrown:

Parse error: syntax error, unexpected T_CLASS, expecting T_STRING or T_VARIABLE or '$'

So I modified the function to:

public function getName(){echo __CLASS__;}

Of course, this just echoes the parent name -- MyAbstract, so it doesn't work. Only thing I've thought of is to override getName() with a new implementation in each extending class, but that doesn't scale well: the whole point of inheritance is to concentrate common codebase in a parent (and of course the real function is not a one-liner).

Any idea how I can dynamically get the extending class name from the context of the abstract parent class in PHP 5.3?

</div>
  • 写回答

2条回答 默认 最新

  • dongzhao5834 2017-09-01 14:35
    关注

    You can use get_class to get the name of class:

    <?php
    abstract class MyAbstract
    {
        public function getName()
        {
            echo get_class($this);
        }
    }
    
    class MyExtends extends MyAbstract 
    {
    }
    
    $c = new MyExtends();
    echo $c->getName(); // expect: "MyExtends"
    

    demo: https://ideone.com/TtMtZ7

    The above code should work on all versions (since 5.0.4).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题