doutou6803 2013-05-06 21:18
浏览 24
已采纳

获取当前正在执行的方法

I'm fairly new to OOP and I'm trying to get the name of the currently executing class and method. For example:

<?php

class ParentExample
{
    function __construct()
    {
        echo get_class($this) . '<br />';
        echo __METHOD__;
        exit;
    }
}

class ChildExample extends ParentExample
{
    public static function test()
    {
        echo 'hello';
    }
}

call_user_func_array([new ChildExample, test]);

This is the result I want:

ChildExample
ChildExample::test

This is the result I get:

ChildExample
ParentExample::__construct

I've looked at debug_backtrace() but I don't understand how to decipher the results or if that's even what I need. Is there an easier way to achieve what I'm after?

EDIT: Based on the answers I think my question isn't clear. I want the ParentExample constructor to tell me the name of the called method. Is this possible?

  • 写回答

2条回答 默认 最新

  • dongliu8542 2013-05-06 21:34
    关注

    I want the ParentExample constructor to tell me the name of the called method. Is this possible?

    No, that is not possible. The constructor is executed when constructing the object and only then, this means it's executed before you can place any method calls on the object.


    echo __METHOD__; is within the __construct method. Since __METHOD__ always has the value of the method it's in, it can't print `

    __construct is called when you create the object. You create an object by using the new operator. This is not connected to the static test method.

    You would have to put echo __METHOD__ into the test method for that to happen ;)

    You should use a string to specify the name of the method:

    call_user_func_array([new ChildExample, "test"]);
    // Since you're not passing any arguments, this will do:
    call_user_func_array([new ChildExample, "test"]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行