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

时间:2013-09-06 11:19:16

标签: php

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

例如:

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!

3 个答案:

答案 0 :(得分:0)

不确定为什么你需要它,但没有什么能阻止你拥有一个可以在课堂内调用的独家private function

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
   }
}

答案 1 :(得分: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块之后,只需输入正常的代码。

答案 2 :(得分:-1)

使用php的get_called_class()函数

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