PHP 5 Classes and Objects
PHP 5 Classes and Objects
PHP 5 Classes and Objects
Contents
1. Introduction 2
2. Sample Exercise (Class) 2
3. Using Constructors 5
4. Using private 6
5. Inheritance Concept 8
6. Using Iinal 10
7. Using Destructors 11
8. getclass() and getparentclass() 12
9. Autoloading Objects 14
10.Visibility 15
11.Scope Resolution Operator (::) 19
12.Static Keyword 21
13.Class Abstraction 22
14.Object Iteration 25
15.Magic Methods 26
16.Patterns 27
17.Late Static Bindings 30
18.Objects and reIerences 34
19.InterIaces 35
20.Exceptions 37
PBP S Classes anu 0bjects Page 2
Introduction
In PHP, a class is simply a set oI program statements which perIorm a speciIic task. A typical class
deIinition contains both variables and Iunctions, and serves as the template Irom which to spawn
speciIic instances oI that class.
These speciIic instances oI a class are reIerred to as objects. Every object has certain characteristics,
or properties, and certain pre-deIined Iunctions, or methods. These properties and methods oI the
object correspond directly with the variables and Iunctions within the class deIinition.
Once a class has been deIined, PHP allows you to spawn as many instances oI the class as you like.
Each oI these instances is a completely independent object, with its own properties and methods, and
can thereIore be manipulated independently oI other objects. This comes in handy in situations where
you need to spawn more than one instance oI an object - Ior example, two simultaneous database
links Ior two simultaneous queries, or two shopping carts.
Classes also help you keep your code modular - you can deIine a class in a separate Iile, and include
that Iile only in the scripts where you plan to use the class - and simpliIy code changes, since you
only need to edit a single Iile to add new Iunctionality to all your spawned objects.
Sample Exercise (Class)
To understand this better, pick an animal, any animal. For example, we can take bear. every bear has
certain characteristics - age, weight, sex - which are equivalent to object properties. And every bear
can perIorm certain activities - eat, sleep, walk, run, mate - all oI which are equivalent to object
methods.
Let's take it a little Iurther. Since all bears share certain characteristics, it is possible to conceive oI a
template Bear(), which deIines the basic characteristics and abilities oI every bear on the planet.
Once this Bear() ("class") is used to create a new $bear ("object"), the individual characteristics
oI the newly-created Bear can be manipulated independently oI other Bears that may be created Irom
the template.
Now, iI you sat down to code this class in PHP 5, it would probably look something like this:
PBP S Classes anu 0bjects Page S
<?php
// PHP 5 // class definition
class Bear {
// define properties
public $name;
public $weight;
public $age;
public $sex;
public $colour;
// define methods
public function eat() {
echo $this->name." is eating...\n";
}
public function run() {
echo $this->name." is running...\n";
}
public function kill() {
echo $this->name." is killing prey...\n";
}
public function sleep() {
echo $this->name." is sleeping...\n";
}
}
?>
<?php
// my first bear
$daddy = new Bear;
// give him a name
$daddy->name = "Daddy Bear";
// how old is he
$daddy->age = 8;
// what sex is he
$daddy->sex = "male";
// what colour is his coat
$daddy->colour = "black";
// how much does he weigh
$daddy->weight = 300;
PBP S Classes anu 0bjects Page 4
// give daddy a wife
$mommy = new Bear;
$mommy->name = "Mommy Bear";
$mommy->age = 7;
$mommy->sex = "female";
$mommy->colour = "black";
$mommy->weight = 310;
// and a baby to complete the family
$baby = new Bear;
$baby->name = "Baby Bear";
$baby->age = 1;
$baby->sex = "male";
$baby->colour = "black";
$baby->weight = 180;
print("<h2>PHP Class and Object Example 1</h1>");
// a nice evening in the Bear family
// daddy kills prey and brings it home
$daddy->kill();
echo "<br/>";
// mommy eats it
$mommy->eat();
echo "<br/>";
// and so does baby
$baby->eat();
echo "<br/>";
// mommy sleeps
$mommy->sleep();
echo "<br/>";
// and so does daddy
$daddy->sleep();
echo "<br/>";
// baby eats some more
$baby->eat();
echo "<br/>";
?>
PBP S Classes anu 0bjects Page S
Using Constructors
It's also possible to automatically execute a Iunction when the class is called to create a new object.
This is reIerred to in geek lingo as a constructor and, in order to use it, your PHP 5 class deIinition
must contain a special Iunction, __construct().
For example, iI you'd like all newly born bears to be brown and weigh 100 units, you could add this
to your class deIinition:
<?php
// PHP 5 // class definition
class Bear {
// define properties
public $name;
public $weight;
public $colour;
public function __construct() {
$this->age = 0;
$this->weight = 100;
$this->colour = "brown";
}
}
?>
<?php
// create instance
PBP S Classes anu 0bjects Page 6
$this->weight = 100;
$this->_lastUnitsConsumed = 0;
}
// define methods
public function eat($units) {
echo $this->name." is eating ".$units." units of food...\n";
$this->weight += $units;
$this->_lastUnitsConsumed = $units;
}
public function getLastMeal() {
echo "Units consumed in last meal were ".$this->_lastUnitsConsumed."\n";
}
}
?>
<?php
$bob = new Bear;
$bob->name = "Bobby Bear";
$bob->eat(100);
$bob->eat(200);
echo $bob->getLastMeal();
// the next line will generate a fatal error
$bob->_lastUnitsConsumed = 1000;
?>
Now, since the $_lastUnitsConsumed variable is declared as private, any attempt to modiIy it
Irom an object instance will Iail. Here is the output:
In a similar way, class methods can also be marked as private.
PBP S Classes anu 0bjects Page 8
Inheritance Concept
Two oI the best things about OOP, whether in PHP 4 or in PHP 5, are extensibility and inheritance.
Very simply, this means that you can create a new class based on an existing class, add new Ieatures
(read: properties and methods) to it, and then create objects based on this new class. These objects
will contain all the Ieatures oI the original parent class, together with the new Ieatures oI the child
class.
As an illustration, consider the Iollowing PolarBear() class, which extends the Bear() class
with a new method.
<?php
// class definition
class Bear {
// define properties
public $name;
public $weight;
public $age;
public $sex;
public $colour;
public function __construct() {
$this->age = 0;
$this->weight = 100;
}
// define methods
public function eat($units) {
echo $this->name." is eating ".$units." units of food...\n";
$this->weight += $units;
}
public function run() {
echo $this->name." is running...\n";
}
public function kill() {
echo $this->name." is killing prey...\n";
}
public function sleep() {
echo $this->name." is sleeping...\n";
}
}
PBP S Classes anu 0bjects Page 9
In this case, the Iinal call to $tom->swim() will Iail and cause an error, because the Bear() class
does not contain a swim() method. However, none oI the calls to $bob->run() or $bob-
>kill() will Iail, because as a child oI the Bear() class, PolarBear() inherits all the methods
and properties oI its parent.
Note how the parent class constructor has been called in the PolarBear() child class constructor -
it's a good idea to do this so that all necessary initialization oI the parent class is carried out when a
child class is instantiated. Child-speciIic initialization can then be done in the child class constructor.
Only iI a child class does not have a constructor, is the parent class constructor automatically called.
Using final
To prevent a class or its methods Irom being inherited, use the Iinal keyword beIore the class or
method name (this is new in PHP 5 and will not work in older versions oI PHP). Here's an example,
which renders the Bear() class un-inheritable (iI that's actually a word):
<?php
// class definition
final class Bear {
// define properties
// define methods
}
// extended class definition
// this will fail because Bear() cannot be extended
class PolarBear extends Bear {
// define methods
}
// create instance of PolarBear()
// this will fail because Bear() could not be extended
$bob = new PolarBear;
$bob->name = "Bobby Bear";
echo $bob->weight;
?>
PBP S Classes anu 0bjects Page 11
Using Destructors
Just as there are constructors, so also are there destructors. Destructors are object methods which are
called when the last reIerence to an object in memory is destroyed, and they are usually tasked with
clean-up work - Ior example, closing database connections or Iiles, destroying a session and so on.
Destructors are only available in PHP 5, and must be named __destruct(). Here's an example:
<?php
// class definition
class Bear {
// define properties
public $name;
public $weight;
public $age;
public $sex;
public $colour;
// constructor
public function __construct() {
$this->age = 0;
$this->weight = 100;
$this->colour = "brown";
}
// destructor
public function __destruct() {
echo $this->name." is dead. He was ".$this->age." years old and
".$this->weight." units heavy. Rest in peace! \n";
}
// define methods
public function eat($units) {
echo $this->name." is eating ".$units." units of food...\n";
$this->weight += $units;
}
public function run() {
echo $this->name." is running...\n";
}
public function kill() {
PBP S Classes anu 0bjects Page 12
}
public function weightt(){
echo $this->name. " is ".$this->weight." Kilo Gram.";
}
}
?>
You can view all the properties exposed by a class with get_class_vars(), and all its methods
with get_class_methods() Iunction. To view properties oI the speciIic object instance, use
get_object_vars() instead oI get_class_vars(). Here is an example:
<?php
$daddy = new DOG;
$daddy->name="Daddy Dog";
$daddy->weight=120;
$daddy->sex="Male";
$daddy->colour="Blue";
print("<br/>");
$class_name = get_class($daddy);
print_r(get_class_vars($class_name));
print("<br/>");
print_r(get_class_methods($class_name));
print("<br/>");
print_r(get_object_vars($daddy));
?>
As noted in one oI the previous segments oI this tutorial, the print_r() Iunction allows you to
look inside any PHP variable, including an object.
PBP S Classes anu 0bjects Page 14
Autoloading Objects
In PHP 5, it is no longer necessary to create one PHP source Iile per-class deIinition while writing
object-oriented application. You may deIine an __autoload Iunction which is automatically called
in case you are trying to use a class/interface which hasn't been deIined yet. By calling this
Iunction the scripting engine is given a last chance to load the class beIore PHP Iails with an error.
Note: Exceptions thrown in __autoload function cannot be caught in the catch
block and results in a fatal error.
Note: Autoloading is not available if using PHP in CLI interactive mode.
Note: If the class name is used e.g. in call_user_func() then it can contain some
dangerous characters such as ../. It is recommended to not use the user-input in
such functions or at least verify the input in __autoload().
The example below attempts to load the class Bear Irom the Iiles Bear.php.
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new Bear();
?>
PBP S Classes anu 0bjects Page 1S
Visibility
The visibility oI a property or method can be deIined by preIixing the declaration with the keywords:
public, protected or private. Public declared items can be accessed everywhere.
Protected limits access to inherited and parent classes (and to the class that deIines the item).
Private limits visibility only to the class that deIines the item.
Members Visibility
Class members must be deIined with public, private, or protected.
<?php
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo "<br/>";
//echo $obj->protected; // Fatal Error
//echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
echo "<br/>";
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';
function printHello()
{
PBP S Classes anu 0bjects Page 16
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublic\n";
}
private function testPrivate() {
echo "Bar::testPrivate\n";
echo "<br/>";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}
private function testPrivate() {
echo "Foo::testPrivate\n";
}
}
$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>
PBP S Classes anu 0bjects Page 19
Static Keyword
Declaring class members or methods as static makes them accessible without needing an
instantiation oI the class. A member declared as static cannot be accessed with an instantiated class
object (though a static method can).
Because static methods are callable without an instance oI the object created, the pseudo variable
$this is not available inside the method declared as static.
Note : Static properties cannot be accessed through the object using the arrow operator -~.
<?php
class Hello
{
public static $my_static = 'testing_hello';
public function staticValue() {
return self::$my_static;
}
}
class Bar extends Hello
{
public function testing_helloStatic() {
return parent::$my_static;
PBP S Classes anu 0bjects Page 22
}
}
print Hello::$my_static . "\n";
$testing_hello = new Hello();
print $testing_hello->staticValue() . "\n";
print $testing_hello->my_static . "\n"; // Undefined "Property" my_static
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->testing_helloStatic() . "\n";
?>
Class Abstraction
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance oI a class that
has been deIined as abstract. Any class that contains at least one abstract method must also be
abstract. Methods deIined as abstract simply declare the method's signature they cannot deIine the
implementation.
When inheriting Irom an abstract class, all methods marked abstract in the parent's class declaration
must be deIined by the child; additionally, these methods must be deIined with the same (or a less
restricted) visibility. For example, iI the abstract method is deIined as protected, the Iunction
implementation must be deIined as either protected or public, but not private.
<?php
abstract class AbstractClass
{
PBP S Classes anu 0bjects Page 2S
OUTPUT
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
A Real time Example Ior Abstract Class
<?php
abstract class person {
abstract protected function write_info();
public $LastName;
public $FirstName;
public $BirthDate;
public function get_Age($today=NULL){
//age computation function
}
}
final class employee extends person{
public $EmployeeNumber;
public $DateHired;
public function write_info(){
echo "Writing ". $this->LastName . "'s info to emloyee dbase table";
//ADD unique mandatory checking unique to EMPLOYEE ONLY
//actual sql codes here
}
}
final class student extends person{
public $StudentNumber;
public $CourseName;
public function write_info(){
echo "Writing ". $this->LastName . "'s info to student dbase table";
//ADD unique mandatory checking unique to STUDENT ONLY
//actual sql codes here
}
}
PBP S Classes anu 0bjects Page 2S
foreach($class as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$class->iterateVisible();
?>
The above example will output:
var1 => value 1
var2 => value 2
var3 => value 3
MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var
Magic Methods
__toString
<?php
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}
public function __toString() {
return $this->foo;
}
}
PBP S Classes anu 0bjects Page 27
Factory
The Factory pattern allows Ior the instantiation oI objects at runtime. It is called a Factory Pattern
since it is responsible Ior "manuIacturing" an object. A Parameterized Factory receives the name oI
the class to instantiate as argument.
Example #1 Parameterized Factory Method
<?php
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
?>
DeIining this method in a class allows drivers to be loaded on the Ily. II the Example class was a
database abstraction class, loading a MySQL and SQLite driver could be done as Iollows:
<?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');
// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>
Singleton
The Singleton pattern applies to situations in which there needs to be a single instance oI a class. The
most common example oI this is a database connection. Implementing this pattern allows a
programmer to make this single instance easily accessible by many other objects.
PBP S Classes anu 0bjects Page 29
Example #2 Singleton Function
<?php
class Example
{
// Hold an instance of the class
private static $instance;
// A private constructor; prevents direct creation of object
private function __construct()
{
echo 'I am constructed';
}
// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example method
public function bark()
{
echo 'Woof!';
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>
PBP S Classes anu 0bjects Page Su
The above example will output:
B
Example #3 static:: usage in a non-static context
<?php
class TestChild extends TestParent {
public function __construct() {
static::who();
}
public function test() {
$o = new TestParent();
}
public static function who() {
echo __CLASS__."\n";
}
}
class TestParent {
public function __construct() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
$o = new TestChild;
$o->test();
?>
The above example will output:
TestChild
TestParent
PBP S Classes anu 0bjects Page SS
$c = new A;
$d = &$c; // $c and $d are references
// ($c,$d) = <id>
$d->foo = 2;
echo $c->foo."\n";
$e = new A;
function foo($obj) {
// ($obj) = ($e) = <id>
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
The above example will output:
2
2
2
InterIaces
Object interIaces allow you to create code which speciIies which methods a class must implement,
without having to deIine how these methods are handled.
InterIaces are deIined using the interIace keyword, in the same way as a standard class, but without
any oI the methods having their contents deIined.
All methods declared in an interIace must be public, this is the nature oI an interIace.
PBP S Classes anu 0bjects Page S6
implements
To implement an interIace, the implements operator is used. All methods in the interIace must be
implemented within a class; Iailure to do so will result in a Iatal error. Classes may implement more
than one interIace iI desired by separating each interIace with a comma.
Example # Interface example
<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
PBP S Classes anu 0bjects Page S7
{
$this->vars[$name] = $var;
}
}
?>
Exceptions
PHP 5 has an exception model similar to that oI other programming languages. An exception can be
thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to
Iacilitate the catching oI potential exceptions. Each try must have at least one corresponding catch
block. Multiple catch blocks can be used to catch diIIerent classes oI exeptions.
When an exception is thrown, code Iollowing the statement will not be executed, and PHP will
attempt to Iind the Iirst matching catch block. II an exception is not caught, a PHP Fatal Error will be
issued with an "Uncaught Exception ..." message, unless a handler has been deIined with
set_exception_handler().
Example #1 Throwing an Exception
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
PBP S Classes anu 0bjects Page S8