doufeng2877 2014-08-13 16:37
浏览 68
已采纳

在PHP中,可以判断parent是否显式调用了一个方法::

Is it possible to tell if a method in the parent class is called explicitly by parent:: as opposed to being called automatically because the sub class doesn't contain the method being called?

  • 写回答

1条回答 默认 最新

  • dsj60862 2014-08-13 17:23
    关注

    well, I'm not sure you can get it easily. anyway, I think you could follow one of this way, if you need a work-around:

    example 1:

    class Par
    
    {
        function printit($which = false)
        {
            // when you call this method, based on variable it tells how it was called
            if ($which) {
                echo "called with parent 
    ";
            } else {
                echo "called with this 
    ";
            }
        }
    }
    
    class Chi extends Par
    
    {
        function callParent()
        {
            parent::printit(TRUE);
        }
    
        function callFunction()
        {
            $this->printit(FALSE);
        }
    }
    
    $chi = new Chi();
    $chi->callParent();
    $chi->callFunction();
    

    example 2:

    class Par
    
    {
        function printit()
        {
            // get all functions in child class
            $child_methods = array_diff(get_class_methods("Chi") , get_class_methods("Par"));
            // if the function there is in child class, probably it was called from there
            if (in_array(__FUNCTION__, $child_methods)) {
                echo "called with child 
    ";
            } else {
                echo "called with parent 
    ";
            }
        }
    }
    
    class Chi extends Par
    
    {
        function callParent()
        {
            parent::printit();
        }
    
        function callFunction()
        {
            $this->printit();
        }
    }
    
    $chi = new Chi();
    $chi->callParent();
    $chi->callFunction();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图