Patrick
Patrick

Reputation: 4905

php class extend - run something before running parent function

say I have this class:

class animal {
   function noise() {
       print 'woof';
   }
   function move() {
       print 'moved';
   }
}

class dog extends animal {

}

What I would like to do is when i run $dog->noise() or $dog->move(), it would run something first prior to calling animal class's noise/move. Is this doable? Like maybe logging the function call. If not with class extend, what else can I use to achieve this?

Thank you!

Upvotes: 0

Views: 1014

Answers (2)

Decent Dabbler
Decent Dabbler

Reputation: 22783

class dog extends animal
{
    function noise()
    {
        /* do stuff here */

        parent::noise();
    }
}

Upvotes: 4

Amber
Amber

Reputation: 526523

Yes - use the parent keyword:

http://php.net/manual/en/keyword.parent.php

class dog extends animal {

    function move() {
        print 'a dog...';
        parent::move();
    }

}

Calling the move() method on a dog will now result in printing "a dog..." and then "moved".

Upvotes: 3

Related Questions