Linas Baublys
Linas Baublys

Reputation: 11

PHP check if method called from extened class

I have code two classes

class old{
    function query(){
        #do some actions ...
    }

    function advancedQuery(){
        #some actions and then
        $this->query();
    }
}

and

class awesome extends old{
   function query(){
        parent::query();

        $fromClassOld = false; # this variable must be changed if method is called from class 'OLD'
        if( $fromClassOld ){
            echo 'foo ';
        }else{
            echo 'bar ';
        }
   }
}

then some usage like this

$awesome = new awesome();
$awesome->query(); # should return 'bar'
$awesome->advancedQuery(); # should return 'foo'

You can check code here http://goo.gl/Gq63Wk

I want that variable $fromClassOld to be changed if method query() is called from class 'old'.

Class old cant be modified.

I found hack by using debug_backtrace() and checking variable debug_backtrace()[0]['file'], but I am preaty sure this could be solved in better way.

Upvotes: 1

Views: 360

Answers (2)

Linas Baublys
Linas Baublys

Reputation: 11

Best thing I could make :

$bt = debug_backtrace();
end($bt);
var_dump($bt[key($bt)]['class']);

Upvotes: 0

Forien
Forien

Reputation: 2763

You cannot. If you call method on child class, then you call method on child class. If you call method on parent class, it has no acces to child's methods. so your advancedQuery() never goes to the awesome::query(), but only to old::query()

All you can do is make another advancedQuery() in awesome class.

Upvotes: 1

Related Questions