0

如何确定是从对象外部还是内部调用方法?

例如:

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!
4

3 回答 3

0

不知道你为什么需要它,但没有什么能阻止你拥有一个private function可以从类内部调用的 Exclusive:

class Example {
   public function Foo(){
      // Always make sure to call private PvtBar internally
      $this->PvtBar();  
   }

   private function PvtBar() {
     // this method was invoked from another method in this object.
     echo 'I\'m talking to myself again.';
     // now call common functionality
     RealBar();
   }

   public function Bar() {
     // this method was invoked from outside the object.
     echo 'I see you\'re an outsider!';
     // now call common functionality
     RealBar();
   }

   private function RealBar() {
     // put all the code of original Bar function here
   }
}
于 2013-09-06T11:27:29.203 回答
0

在您调用的方法中,立即抛出并捕获异常,如下所示:

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 块之后,只需输入您的正常代码。

于 2013-09-06T14:04:45.763 回答
-1

使用 php 的 get_call_class() 函数

它将返回类名。如果从类外部调用,将返回 FALSE。

于 2013-09-06T11:25:02.210 回答