Search code examples
phpclassfunctioninternal

If function called internally


Is there any way of identifying if a function was called from within the same class in PHP? Besides using something like debug_backtrace ?

Update:

This is what I'm currently doing:

class Alex {
  function __construct()
  {
     $this->internal = false;
  }

  function a()
  {
    $this->internal = true;
    $this->b();
  }

  function b()
  {
    if($this->internal) 
      // ...
    else
      // ...
  }
}

Solution

  • I 'm not sure why you would want to do that; this kind of requirement is suspicious, and usually for good reason.

    That said, you can make a protected clone of the public function with an additional parameter that tells you if the caller was internal or external, and make the public version defer to the protected implementation.

    class Before
    {
        public foo() { /* code here */ }
    }
    
    class After
    {
        public foo() { $this->fooCore(false); }
        protected fooCore($calledFromInside = true) { /* code here */ }
    
        // At this point you should make sure that you never call $this->foo()
        // directly from inside class After
    }