rsk82
rsk82

Reputation: 29377

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

Example code:

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

Upvotes: 1

Views: 195

Answers (3)

dnagirl
dnagirl

Reputation: 20456

It might be easier, rather than detecting from whence the function was called, to wrap a private function with a public one. Like so:

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

Upvotes: 3

Cyclone
Cyclone

Reputation: 18285

You could add an optional parameter like such:

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

and leave that last. If you are calling it from inside the class, pass it true, otherwise pass nothing!

Upvotes: 0

sergio
sergio

Reputation: 69027

You can try and get the caller of your method:

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

this should work for you.

Upvotes: 2

Related Questions