Overriding Methods

Methods within a child class can override the parent class, simply by redefining your own version.

 

 

The parent's display method on line 5 is overridden in the child's redefinition on line 13:

<?php
	class ParentClass {
		public $name;

		public function display() {
			$output = $this->name;
			$output .= "Just some random text that's going to be overridden!";
			return $output;
		}
	}
	class ChildClass extends ParentClass {

		public function display() {
			$output = $this->name;
			$output .= " \"Legendary\" NYC Goth DJ!";
			return $output;
		}
	}
	$myChild = new ChildClass;
	$myChild->name = "Vanessa Miasma";
	echo $myChild->display();
	?>

Save & refresh browser:

Vanessa Miasma "Legendary" NYC Goth DJ!

Leave a Reply