drqvsx1228 2015-01-20 03:16 采纳率: 0%
浏览 70
已采纳

是否有可能获得在PHP中扩展另一个类的类/文件的名称?

I have a PHP website which has two core php files ci_controller.php and my_controller.php and a number of controller php files. My_Controller class extends CI_Controller. The other contoroller PHP classes extend My_Controller.

I was wanting to change the website so that some of the thing My_Controller class will only occur for some of the classes which extended. i.e. depending on which class extended My_Controller do x.

I was wondering if it is possible to use the parent/child relationship (or see which files extend a class) to create an if/exception so that some of the My_Controller parts on run for certain PHPs?

For example if a three classes;

  • classA, classB and classC.
  • classA and classB both extend classC (i.e class classA extends classC)

In this example I want to have a line in classC which does the following pseudo code:

if (extended by classA)
{//do something}
else if (extended by classB)
{//do something else}

NOTE: Two similar questions on stackoverflow are:

However they do not solve my problem, but maybe helpful for those looking for a similar solution

  • 写回答

2条回答 默认 最新

  • doubo9799 2015-01-20 22:27
    关注

    Very simple:

    class MyController {
    
        public function someFunc() {
            if ($this instanceof ClassA || $this instanceof ClassB) {
                ...
            }
        }
    
    }
    

    BUT: This is a horrible design. A parent should not know about its children and specialise its behaviour depending on who extends it. It needs to be the other way around. The parent provides some functionality and the children each use it as necessary. Turn it around and only call a parent function from a specific child, and don't call it from other children:

    class MyController {
        public function foo() { .. }
    }
    
    class ClassB extends MyController {
        public function __construct() {
            $this->foo();
        }
    }
    
    class ClassD extends MyController {
        public function __construct() {
            // simply don't call
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码