PHP Object Oriented Programming

From Techotopia
Revision as of 19:51, 6 June 2007 by Neil (Talk | contribs) (PHP Class Constructors and Destructors)

Jump to: navigation, search

PHP provides extensive support for developing object-oriented software. The area of object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. As such, a detailed overview of object oriented software development is beyond the scope of this PHP book. Instead we will introduce the basic concepts involved in object oritent programming and thyen move on to explaining the concept in related to PHP development.


Contents


What is an Object?

An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application.

Objects consist of data variables (called members) and functions that can be called on the object to perform tasks (called methods).

What is a Class?

Much like a blueprint or architect's drawing defines what an item or a building will look like once it has been contructed, a class defines what anm object will look like when it is created. It defines, for example what the methods will do and what thge member variables will be.


How is an Object Created from a Class?

The process of creating an object from the class 'blueprint' is called instantiation. Essentially you instiate an isntance of the class and give that instance a name by which you will refer to it when acessing members and calling methods. You can create as many object instances of a class as you desire. Objects are instantiated using the new keyword. For example to create an instance of a class called bankAccount you would write:

$accountObject = new bankAccount();

In the above example we now have an object called $accountObjhect of type bankAccount.

What is sub-classing?

It is possible to build class that are derived from other classes, extending the functionality of the parent class to make it specific to a particular requirement. For example you might have a vehicle class which contains the attributes common to all vehicles, and a sub-class called car which inherits all the generic vehicle attributes but adds some its own car specific methods and properties.

Defining a PHP Class

Before an object can be instantiated we first need to define the class 'blueprint' for the object. Classes are defined using the class keyword following by braces which will be used to enclose the body of the class:

<?php
class bankAccount {
}
?>

We have now defined a class. The next step is add some functionality to the class.

PHP Class Constructors and Destructors

The next step in creating a class is to define what should happen when an object is first instantiated using the class, and also when that object is later destroyed. These actions are defined the constructor and destructor methods of the class.

The constructor and destructor are really just functions that get called when the object is created and destroyed and are defined in the class body using the function keyword. This needs to be prefixed with the public qualifier. This means the method is accessible to code outside of the object. The default names fo rthe constructor and destructor are __construct and __destruct respectively. Both methods can take arguments to be used in initializing the object. These are declared in the same way arguments are defiend in any function (see PHP Functions for details).

We can now expend out bankAccount class to include a constructor and destructor:

<?php
class bankAccount {

   public function __construct($accountNumber, $accountName) {
         echo 'Object was just instantiated. Number = $accountNumber, Name = $accountName <br>';
   }

   public function __destruct() {
         echo 'Object was just destroyed <br>';
   }

}
?>

When the example is loaded into a browser we should get the following output:

Object was just instantiated. Number = 123456, Name = Gregory House
Object was just destroyed

Creating Members in a PHP Class

Class members are essentially variables and methods embedded into the class. Members can be public or private and static or variable.

public members can be accessed from outside the object. private members can only be accessed by methods contained in the class. This the key to what is called data encapsulation. Object-oriented programming convention dictates tha data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters).

Members declared as static are immutable, in that once defined athey cannot be changed (much like constants). Members fuinctions are prefixed with public, private and static when declared in the class. TYhe default is public non-static.

We can now extend out bankAccount class to add member variables to hold the account name and number passed inot the constructor. True to the concept of data encapsulation we will be created methods to access these values later, so will mark them as private. We will also add to our constructor to assign the passed arguments to our new members. When doing so we need to use the $this variable to tewll PHP we are setting variables in the current class:

<?php
class bankAccount {

   private $accountNumber;
   private $accountname;

   public function __construct($acctNumber, $acctName) {
        $this->accountNumber = $acctNumber;
        $this->accountname = $acctName;
   }

   public function __destruct() {
         echo 'Object was just destroyed <br>';
   }

}
        $myObj = new bankAccount('123456', 'Gregory House');
?>

The next task is to defione methods that will give us access to our data.

Defining and Calling Methods

We define our own methods in much the same way as the declare the constructor and destructor methods with exceptionm that we get to choose the names.

To demonstrate this we will add to our class to provide methods to get and set the account number and name:


<?php
class bankAccount {

   private $accountNumber;
   private $accountname;

   public function __construct($acctNumber, $acctName) {
        $this->accountNumber = $acctNumber;
        $this->accountname = $acctName;
   }

   public function __destruct() {
         echo 'Object was just destroyed <br>';
   }

   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;
   }

}
?>

Now that we have defined our getter and setter methods to get and set the account values we can call the methods. This is done by specifying the name of the object on whic the methods are being called, followed by '->' then the name of the method we are calling (including the parentheses containing any arguments required):

<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;
   }

}
        $myObj = new bankAccount('123456', 'Gregory House');

        $myObj->setAccountNumber('654321');

        $accountNumber = $myObj->getAccountNumber();

        echo "New Account Number is $accountNumber";

?>

The above example sets the account name and number when instantiating the object. It then calls the setAccountNumber method of the object to change the account number, followed by a call to getAccountNumber (to verify the change), thereby producing the following output:

New Account Number is 654321