如何确定方法是从对象外部还是从对象内部调用?
例如:
class Example{
public function Foo(){
$this->Bar();
}
public function Bar(){
if(this_function_was_called_from_outside_the_object){
echo 'I see you''re an outsider!' // this method was invoked from outside the object.
}else{
echo 'I''m talking to myself again.'; // this method was invoked from another method in this object.
}
}
}
$oExample = new Example();
$oExample->Foo(); // I''m talking to myself again.
$oExample->Bar(); // I see you''re an outsider!
在你调用的方法中,抛出并立即捕获一个异常,如下所示:
public function test()
{
try
{
throw new Exception("My Exception");
}
catch(Exception $e)
{
//check the stack trace at desired level
//print_r($e->getTrace());
}
//Your code here
}
在 catch 块中,您可以浏览堆栈跟踪并查看谁调用了该方法。在这个 try/catch 块之后,只需输入您的正常代码即可。
使用 php 的 get_called_class() 函数
它将返回类名。如果从类外部调用,将返回 FALSE。