/ Published in: PHP
These are important object oriented principles (OOP) that one must understand in PHP to create dynamic web applications. I hope you find this useful in understanding inheritance.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php /* * Author: Alvin Crespo * Date: 2/23/2010 * * Employee Class is the parent for the Manager subclass * * */ class Employee{ protected $fname; //protected variables and functions are passed to the subclass protected $lname; protected $salary = 32000; protected $position; function __construct($firstname, $lastname, $position){ /* * Methods pertaining to this class * * */ $this->SetFirstName($firstname); $this->SetLastName($lastname); $this->SetPosition($position); } /* * User Private Information * * */ protected function SetLastName($lastname){ $this->lname = $lastname; } protected function SetFirstName($firstname){ $this->fname = $firstname; } public function GetFirstName(){ return $this->fname; } public function GetLastName(){ return $this->lname; } /* *User Work Information * * */ protected function SetSalary($salary){ $this->salary = $salary; } public function GetSalary(){ return "$".$this->salary; } protected function SetPosition($position){ $this->position = $position; } public function GetPosition(){ return $this->position; } function __destruct(){ } } ?> <?php /* * Author: Alvin Crespo * Date: 2/23/2010 * * Class Manager is a sublass to Employee * * */ class Manager extends Employee{ function __construct($fname, $lname){ /* * These methods are located in the parent class Employee * * */ $this->SetLastName($lname); $this->SetFirstName($fname); $this->SetSalary(48000); $this->SetPosition('Manager'); } function __destruct(){ } } ?> /* This is what you would do in your .php file calling these functions*/ <?php require_once 'classes/Employee.php'; require_once 'classes/Manager.php'; $employee = new Employee('jack','smith','Copywriter'); echo "First Name: " . $employee->GetFirstName(); echo "<br/>"; echo "Last Name: " . $employee->GetLastName(); echo "<br/>"; echo "Salary: " . $employee->GetPosition(); echo "<br/>"; echo "Salary: " . $employee->GetSalary(); echo "<br/><br/>"; $manager = new Manager('frank','josom'); echo "First Name: " . $manager->GetFirstName(); echo "<br/>"; echo "Last Name: " . $manager->GetLastName(); echo "<br/>"; echo "Salary: " . $manager->GetPosition(); echo "<br/>"; echo "Salary: " . $manager->GetSalary(); ?>