douyi3632 2014-09-12 08:35
浏览 108
已采纳

从类引用中获取类名称空间和名称,而不更改我的类

In php you often check if the object you get is of the correct type. If not you throw an exception with a message like this:

use My\Class\MyClass

...

if (!$object instanceof MyClass) {
    throw new Exception(
        sprintf(
            "object must be of type '%s'", 
            'My\Class\MyClass'
        )
    );
}

Right now I pass the full namespace and the name of the class in a string to sprintf.

How can I get this from the class reference so that i can do something like this

sprintf("object must be of type '%s'", MyClass::getName())

EDIT:

I would like to achieve this for all classes without adding new methods. So it should be a solution using some existing method or one of the php __ MAGIC__ methods.

  • 写回答

2条回答 默认 最新

  • duandi5328 2014-09-12 09:46
    关注

    As of php 5.5 there's a magic constant that gives you the FQCN of any class. You can use it like this:

    namespace My\Long\Namespace\Foo\Bar;
    
    MyClass::class;
    // will return "My\Long\Namespace\Foo\Bar\MyClass"
    

    It's documented on the new features page.

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

报告相同问题?

悬赏问题

  • ¥100 速求!商品购买力最优化问题(用遗传算法求解,给出python代码)
  • ¥15 虚拟机检测,可以是封装好的DLL,可付费
  • ¥15 kafka无法正常启动(只启动了一瞬间会然后挂了)
  • ¥30 使用matlab将观测点聚合成多条目标轨迹
  • ¥15 Workbench中材料库无法更新,如何解决?
  • ¥20 如何推断此服务器配置
  • ¥15 关于github的项目怎么在pycharm上面运行
  • ¥15 内存地址视频流转RTMP
  • ¥100 有偿,谁有移远的EC200S固件和最新的Qflsh工具。
  • ¥15 有没有整苹果智能分拣线上图像数据