PHP5 OOP

PHP 5 makes some significant improvements on the Object Orientated programming model of PHP 4, bringing it more in line with languages such as VB.NET and Java. The improved object model in PHP 5 makes developing applications using OOP much easier and gives you, the programmer greater flexibility.

Class Definition

Class is a blue print for an Object. A class does not represent an object. It represents all the information a typical object should have as well as all the methods it should have.

Defining the Class

The basic unit of code in object-oriented PHP is the class. Defining a class in PHP5 is a relatively straightforward process. It is similar to defining a function.

Class Round
{

 //  Round code goes here
}

The code defines a simple class by using the class keyword, followed by the name of the class and a set of curly braces.

In PHP5 there are two main parts to a class definition. Properties and methods. Properties represent the data held in the object, while the methods perform actions with that data.

Properties

When you are creating a class in PHP5, properties are where you will store the various bits of data the object will represent.

To define a property in PHP5 is simple as follows.

Visibility $propertyname;

Visibility represents the code visibility of the property, which is one of three values public, private, or protected.

The second of the property definition, propertyname is simple name that your property has to have.

For example, you want to create a class name called round. If that class wants to hold a public property called radius, then the code looks like this.

class Round
{
 public $radius;

}

You can also specify the initial value for the property.  Suppose you want to se the initial radius of your Round set to 20, and then your code looks like this.

class Circle

{
  public $radius = 20;
}

Methods

Code found inside the class to perform the actions. To define method in PHP5 is very similar to creating a standard function inside the class.

Visibility function function_name (parameters)
{
   // method implementation here
}

Similarly to the property definition, method definitions require a visibility component.

We will add a method to calculate the area of the circle.

Class Circle
{
public $radious;

public function round_area($radius)
{
return pi() * pow($radius, 5);
}
}

In the above code we simply created a method called round_area() that takes a parameter $radius, and return the area of a round with the given radius.

Creating a class instances

If you want to access the properties and methods of a class, you first need to instanciate, or create instance of the class.  When a class is instantiated, it returns an individual object of that class type that you can use. In PHP5 instances are created using the new keyword.

$k = new round();

Once the object is created, methods and properties can be accessed by using an “arrow”operator.

Now we will see how to access the properties and methods of a class.

<?
Class Round
{
   public $radius;
        public function check_area($radius)
        {
              return pi() = pow($radius, 2);
         }
 }

// now we will create an instance of a round

 
$r = new  Round();

//changing the property of the value

$c->radius = 10;
// using the method
echo ‘The area of the round is ‘. $c-> check_area(10);
?>

If you run the code in the browser you can view the result as shown below.

The area of the Round is 78.5398167677

When you observe the code you’ll see first class Round. Then we added the code that instantiates the object.

// now we will create an instance of a round
   $r = new  Round();

Last we have changed the $radius property to a value of 10, and calculated the area of a given radius of 10.

$c->radius = 10;

// using the method

echo ‘The area of the round is ‘. $c-> check_area(10);

Constructors and Destructors

A constructor is nothing more then a specially named method that is atomically called when an object is instantiated. In PHP5 to create a constructor you need a method named _constructor. We will see quick example, how to create a constructor.

<php
class Round
{
    public function  _construct()
    {
        // Execute actions when object is created
        echo “Round object is created. \n”;
     }
}

    $r = new Round();
?>

When you view the code in the browser you can notice the following information.

Round object is created.

Now we can perform actions when an object is created, similarly you can also destroy the object, PHP5 includes a special method that is called an object is destroyed, that is destructor. An object’s destructor is called when all the references to an object are removed. Or you can destroy in our code.  To create a destructor add a method to you class, and call it _destruct.

<php
class Round
{
    public function  _construct()
    {
        // Execute actions when object is created
        echo “Round object is created. \n”;
     }

public function _destruct()
{
  // Execute the actions when the object is destroyed

  echo “Round object is being destroyed \n”;
}
}

    $r = new Round();
?>

When you run the code from the browser you can notice the following information.

Round object is created

Round object is being destroyed

Static Keyword

Declaring class members or methods as static, makes them callable from outside the object context. A member or method declared with static cannot be accessed with a variable that is an instance of the object and cannot be re-defined in an extending class.

The static declaration must be after the visibility declaration. For compatibility with PHP 4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public static.

Because static methods are callable without an instance of the object created, the pseudo variable $this is not available inside the method declared as static.

In fact static method calls are resolved at compile time. When using an explicit class name the method is already identified completely and no inheritance rules apply. If self do the call then self is translated to the current class that is the class the code belongs to. Here also no inheritance rules apply.

Static properties cannot be accessed through the object using the arrow operator ->.

Static member example

<?php
class Abc
{
    public static $my_static = 'abc';
    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Abc
{
    public function abcStatic() {
        return parent::$my_static;
    }
}

print Abc::$my_static . "\n";

$abc = new Foo();
print $abc->staticValue() . "\n";
print $abc->my_static . "\n";      // Undefined "Property" my_static

// $abc::my_static is not possible
 
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->abcStatic() . "\n";
?> 

Static method example

<?php
class Abc {
    public static function newStaticMethod() {
        // ...
    }
}
Abc::newStaticMethod();
?> 

Class Constants

Class constants are similar to regular PHP constants, but re available only within the definition of a class. Like standard PHP constants, their value can be set only once to a scalar value.

<?php
class Abc
   const constant = "constant";
}
echo "Abc::constant = " .Abc::constant . "\n";
?>


Inheritance

Inheritance is a form of software reusability in which new classes are created from the existing classes by absorbing their attributes and behaviors.  Instead of defining completely (separate) new class, the programmer can designate that the new class is to inherit attributes and behaviors of the existing class (called superclass). The new class is referred to as subclass.

Programmer can add more attributes and behaviors to the subclass, hence, normally subclasses have more features than their superclasses.

Extends Keyword

A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.

The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them within the same name defined in the parent class. It is possible to access the overrided method or members by referencing them with parent::

Simple Class Inherintance

<?php
class ExtendClass extends SimpleClass
{
   // Redefine the parent method
   function displayVar()
   {
       echo "Extending class\n";
       parent::displayVar();
   }
}

$extended = new ExtendClass();
$extended->displayVar();
?> 

The above example will output:

Extending class
a default value

Interfaces

Another new object oriented feature in PHP5 is interfaces.  An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

<?php
interface new_gameimp {
   public function getMessage();
}

class MyException implements new_gameimp {
   public function getMessage() {
       // ...
   }
}
?>


Solution

In this article we have learned object oriented programming with PHP5.  Using PHP5 you can write  any project- no matter how large or complex. Using PHP 5's new object model, you can  design powerful patterns, improved XML Web services support, and much more.



Language: PHP
OS: Independent
Level: Beginner



Added on September 30, 2007 Comment

Comments

Post a comment

Your name:

Comment: