Quick Question on Overriding Methods

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
s992
Forum Contributor
Posts: 124
Joined: Wed Oct 27, 2010 3:06 pm

Quick Question on Overriding Methods

Post by s992 »

I'm pretty sure I already know the answer, but it doesn't hurt to ask.

If I am overriding a method for the sole purpose of changing one line(playing with CodeIgniter, and I want to leave the core intact), is it necessary to repeat the entire method in my new class?

For example:

Code: Select all

class SomeClass {

	function foo() {
		$var = "bar";
		echo $var;
	}
}

class AnotherClass extends SomeClass {
	
	function foo() {
		$var = "foo";
	}
}

$SomeClass->foo();
$AnotherClass->foo();
Calling SomeClass->foo() will echo "bar," but calling AnotherClass->foo() will not echo anything, correct?

To rephrase my question: does overriding a method completely destroy everything in the existing method and replace it with my new method, or does it just "tack on" the new code?

Thanks in advance!
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Quick Question on Overriding Methods

Post by Darhazer »

it completely overrides the method, but you still can execute the existing method, by calling parent::foo()
In your example calling parent::foo() will still output bar and not foo. This will do the trick:

Code: Select all

class SomeClass {
protected $_message = 'bar';
        function foo() {
                echo $this->_message;
        }
}

class AnotherClass extends SomeClass {
        
        function foo() {
                $this->_message = "foo";
                parent::foo();
        }
}

$SomeClass->foo();
$AnotherClass->foo();
Post Reply