douyu4535 2010-03-02 22:47
浏览 8
已采纳

php获取类的名称

Is there a way for a class called inside another to know the name of the outer class?

Example:

class A{
  // need to get the name of B
  // some stuff
}

class B{
  $var = new A;
}

get_parent_class() qon't do the work since B is not a child of A.

Any suggestions?

Edit: Sorry everyone I had to change the question. What I wanted to ask is can class A know the name of the class in which it is being called. Again sorry for idiotic first question.

  • 写回答

4条回答 默认 最新

  • dongrao9454 2010-03-02 22:49
    关注

    Nope, it's impossible.

    Well, almost. You could hack your way to the calling class from debug_backtrace or apd_callstack, but that is rather inefficient and slow. Xdebug has a number of functions that could help you achieve this too, but all of this is nothing you want in production code.

    The easiest way would be to pass the instance of B to A, e.g.

    class A {
        protected $callerInstance;
        protected $callerClassName
        public function __construct($caller) {
            $this->callerInstance = $caller;
            $this->callerClassName = get_class($caller);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)