Jump to content

if(function is called from child class)?


uckc

Recommended Posts

Is there any built-in function or any way to check if a class method is called from parent class or child class?

 

Example:

class ParentClass {

  __construct(...){

        ...

  }

  function ABC(...){

      if(function called from child){

          echo "called from child";

      }else{

          echo "called from parent";

  }

}

 

class ChildClass {

  __construct(...){

        ...

  }

  function CBA(...){

      ...

      parent:ABC(...);

}

 

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/178870-iffunction-is-called-from-child-class/
Share on other sites

With PHP 5.3.0 came get_called_class() which might be suitable.

 

<?php

class ParentClass {
    public function test() {
        if (__CLASS__ != get_called_class()) {
            echo "Called from child  (" . get_called_class() . ")\n";
        } else {
            echo "Called from parent (" . __CLASS__ . ")\n";
        }
    }
}

class ChildClass extends ParentClass { }
class GrandChildClass extends ChildClass { }

$parent = new ParentClass;
$child  = new ChildClass;
$grand  = new GrandChildClass;

$parent->test();
$child->test();
$grand->test();

?>

 

Called from parent (ParentClass)
Called from child  (ChildClass)
Called from child  (GrandChildClass)

 

If not, as Mark said it will probably be a job for debug_backtrace().

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.