Page 1 of 1

Quick Question on Overriding Methods

Posted: Tue Jan 04, 2011 11:42 pm
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!

Re: Quick Question on Overriding Methods

Posted: Wed Jan 05, 2011 2:57 am
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();