Jump to content

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().

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.