jcadima
7/28/2017 - 12:50 AM

Inheritance

Inheritance

<?php
/*
=========== INHERITANCE ============
*/

class Car {
	// private $model; // SportsCar will not have access to this property
	protected $model; // this will work 

/*	THIS METHOD CAN NOT BE OVERRIDEN BY THE CHILD CLASS
	final public function hello() {
		echo 'FINAL: I am a ' . $this->model; 
	}
*/
	public function hello() {
		echo 'PARENT: I am a ' . $this->model; 
	}
	
	public function setModel( $model ) {
		$this->model = $model;
	}
	
}

class SportsCar extends Car {
	
	// this method overrides the hello method from its parent
	public function hello() {
		echo 'CHILD: I am a ' . $this->model ;
		
	}
}

// test
$sport1 = new SportsCar()  ; 
$sport1->setModel('BMW') ;
$sport1->hello() ;

echo PHP_EOL;

// EXAMPLE 2

class User {
	
	protected $username;
	
	public function setUsername( $uname ) {
		$this->username = $uname ; 
	}
	
}

class Admin extends User {
	public function sayHello() {
		return 'Hello admin, ' . $this->username;
	}
} 

$admin1 = new Admin() ;
$admin1->setUsername('armadillo') ;
echo $admin1->sayHello() ;