Changes

PHP Object Oriented Programming

1,918 bytes added, 20:06, 6 June 2007
Defining and Calling Methods
<tt>New Account Number is 654321</tt><br>
 
== Subclassing in PHP ==
 
Once a class has been defined it is possible to create a new class dirived from it that extends the functionality of the original class. The parent class is called the ''superclass'' and the child the ''subclass''. The whole process is referred to as 'subclassing''.
 
A subclass of a class can be defined using the ''extends'' keyword when declaring the subclass. For example we might choose to create a subclass of of our ''bankAccount'' class called ''savingsAccount'' which defines an interest bearing type of account:
 
<pre>
<?php
class savingsAccount extends bankAccount {
 
private $interestRate = 5;
 
}
 
The important point to note here is that savingsAccount inherits all the members and methods of bankAccount and adds a new member (the interest rate).
 
We can extend the class further by adding a new method to return the interest rate:
 
<pre>
<?php
class bankAccount {
 
private $accountNumber;
private $accountname;
 
public function __construct($acctNumber, $acctName) {
$this->accountNumber = $acctNumber;
$this->accountname = $acctName;
}
 
public function __destruct() {
}
 
public function setAccountNumber($acctNumber)
{
$this->accountNumber = $acctNumber;
}
 
public function setAccountName($acctName)
{
$this->accountName = $acctName;
}
 
public function getAccountName()
{
return $this->accountName;
}
 
public function getAccountNumber()
{
return $this->accountNumber;
}
 
}
 
 
class savingsAccount extends bankAccount {
 
private $interestRate = 5;
 
public function getInterestRate()
{
return $this->interestRate;
}
 
}
 
$mySaveObj = new savingsAccount('246810', 'Morgan Freeman');
 
echo "Savings Account Number is " . $mySaveObj->getAccountNumber() . '<br>';
 
echo "Interest Rate = " . $mySaveObj->getInterestRate() . '<br>';
?>