是否可以确定一个方法是从类内部还是外部调用的


Is it possible to determine whether a method was called from inside or outside of a class?

示例代码:

class MyClass {
    function echo_msg {
        echo // now what...
    }
    function echo_from_inside {
        $this->echo_msg()
    }
}
result should be:
$my_instance = new MyClass();
$my_instance->echo_msg(); // I was called from OUTside
$my_instance->echo_from_inside(); // I was called from INside

用公共函数包装私有函数可能比检测函数的调用位置更容易。像这样:

class MyClass{
  private function myob(){
    //do something
  }
  public function echo_msg(){
    $this->myob();
    //do other stuff like set a flag since it was a public call
  }
  private function foo(){ //some other internal function
    //do stuff and call myob
    $this->myob();
  }
}
$obj=new MyClass();
$obj->echo_msg();//get output
$obj->myob();  //throws error because method is private

您可以尝试获取方法的调用方:

$trace = debug_backtrace();
$caller = array_shift($trace);
echo 'called by '.$caller['function']
echo 'called by '.$caller['class']

这应该对你有用。

您可以添加这样的可选参数:

function echo_msg($ins=false) {
        if($ins){/*called from inside*/}else{/*called from outside*/}
        echo // now what...
    }

最后离开。如果您从类内部调用它,请将其传递给true,否则不传递任何内容!