php - 检查构造函数是否由类实例调用类函数

时间:2017-01-21 16:11:08

标签: php oop

是否可以做这样的事情:

SELECT COL1 as salary, COL1 as money
FROM employees
WHERE salary = '3000' OR money = '5000'

我正在尝试使用class conditional { function __construct() { if (launch() is called) { //return True //function is called by class instance }else{ //return False //launch() is not called } } public function launch(){ echo "function is launcher"; } } 中的条件来了解类实例或对象是否将类函数调用为class constructor。如果$class_instance->launch()未调用function,则应运行返回class instance条件。

1 个答案:

答案 0 :(得分:2)

我认为你不能做你想做的事(我也不明白为什么会这样做)。

在您能够调用任何实例方法之前,构造函数将在您创建实例时运行。除非你有办法深入研究未来,并且在实例化时知道以后是否会调用任何实例方法,否则没有骰子:)

但你可以使用__call魔术方法做一些或多或少的事情,即使在大多数情况下可能没有多大意义。

,例如,非常简化的实施:

class Magical {

   public function __call($method, $args) {

       switch($method) {
          case "launch":
             echo "magical launch() was called\n";
             $this->magicLaunch();
             break;
          default:
             throw new \Exception("Method not implemented");
       }
  }

  private function magicLaunch() {
      echo "magic!";
  }
}


// this is the only point where the constructor gets called
$magic = new Magical();

// since the launch method doesn't exist, the magic method __call is invoked
$magic->launch();

输出:

  

神奇的启动()被称为

     

魔法!