PHP has some support for object-oriented programming. As shown below, it is possible to declare a class that has variables, constructors and functions.
Here is a file (called person.php) that declares a class called Person:
0510: <?php 0511: class Person { 0512: var $iName, $iAge; 0513: function Person($pName, $pAge) { 0514: $this->iName = $pName; 0515: $this->iAge = $pAge; 0516: } 0517: function getName() { 0518: return $this->iName; 0519: } 0520: function setName($pName) { 0521: $this->iName = $pName; 0522: } 0523: function getAge() { 0524: return $this->iAge; 0525: } 0526: function setAge($pAge) { 0527: $this->iAge = $pAge; 0528: } 0529: function hasSameAge($pPerson) { 0530: return $this->iAge==$pPerson->getAge(); 0531: } 0532: function display() { 0533: echo "<P>$this->iName's age is $this->iAge</P>\n"; 0534: } 0535: } 0536: %>
And here is a file (called persontest.php) that declares and uses objects that are of this class:
0537: <?php 0538: require("person.php"); 0539: // tom and dick 0540: $tFirstPerson = new Person("tom", 25); 0541: $tFirstPerson->display(); 0542: $tSecondPerson = new Person("dick", 24); 0543: $tSecondPerson->display(); 0544: $tSameAge = $tFirstPerson->hasSameAge($tSecondPerson); 0545: if ($tSameAge) 0546: echo "<P>they have the same age</P>\n"; 0547: else 0548: echo "<P>they have different ages</P>\n"; 0549: // fred and barney 0550: $tFirstPerson = new Person("fred", 55); 0551: $tFirstPerson->display(); 0552: $tSecondPerson = new Person("barney", 55); 0553: $tSecondPerson->display(); 0554: $tSameAge = $tFirstPerson->hasSameAge($tSecondPerson); 0555: if ($tSameAge) 0556: echo "<P>they have the same age</P>\n"; 0557: else 0558: echo "<P>they have different ages</P>\n"; 0559: %>
Go to the script at: http://www.dur.ac.uk/barry.cornelius/papers/phpintro/code/persontest.php
In a paper entitled 'The Object Oriented Evolution of PHP', Zeev Suraski explains some of the limitations of PHP 4 and outlines what is likely to be provided in PHP 5.
Some of the limitations of PHP 4 are:
0560: $tFirstPerson->iAge = 24;
Many of the above limitations are being removed in PHP 5. Beta 2 of PHP 5.0.0 has been released. Probably, the most up-to-date statement about the OO features of PHP 5 can be found at: http://www.php.net/zend-engine-2.php. Here is a summary of some of the new features in PHP 5:
Suraski's paper is at: http://www.zend.com/images/press/Feb_2003-4_Zeev_PHP5.pdf. Another useful paper is at: http://www.zend.com/engine2/ZendEngine-2.0.pdf