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

How do I determine if a method is called from outside of an object or from inside?

For Example:

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!

use get_called_class() function of php

It will return the class name. Will return FALSE if called from outside a class.

Not sure why you need it but nothing stops you to have an exclusive private function, that can be called from inside the class:

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

In the method you call, throw and catch immediatly an exception, like this :

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
}

In the catch block, you can browse the stack trace and see who called the method. After this try/catch block, just put your normal code.