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条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line