This page provides a brief overview of objects in PHP. It is by no means comprehensive so if you need more information, please see the PHP documentation.
To begin with, the following is a simple address object. It has two member variables $name
and $street
. Both members have a visibility of private
. There are three possible visibility values in PHP5.
private
- Only the class can access the member or method.protected
- Only parent and inherited classes have access.public
- The member or method can be accessed from anywhere.
If visibility is undefined, the default it public
. Take a look at the class. Additional comments follow the code sample.
Demo: object01.php
Source: object01.php
1:<?php
2:error_reporting(E_ALL);
3:
4:class Address{
5: // Members
6: private $name = '';
7: private $street = '';
8:
9: // Methods
10: function __construct($newName, $newStreet){
11: $this->name = $newName;
12: $this->street = $newStreet;
13: }
14:
15:
16: public function display(){
17: echo "<h4>Address Entry</h4>\n";
18: echo "<p>\n";
19: echo "<b>Name: </b>" . $this->name . "<br/>\n";
20: echo "<b>Street: </b>" . $this->street . "<br/>\n";
21: echo "</p>\n";
22: }
23:
24: public function getName(){
25: return $this->name;
26: }
27:
28: public function setName($newName){
29: $this->name = $newName;
30: }
31:
32: public function getStreet(){
33: return $this->street;
34: }
35:
36: public function setStreet($newStreet){
37: $this->street = $newStreet;
38: }
39:
40:}
41:
42:?>
43:<html>
44:<head>
45: <title>PHP Address Object</title>
46:</head>
47:<body>
48: <h2>PHP Address Object</h2>
49: <p>Create an object and display it.</p>
50: <?php
51: $anAddress = new Address("John Doe", "1234 1st St");
52: $anAddress->display();
53: ?>
54: <p>Change the object contents and display them.</p>
55: <?php
56: $anAddress->setName("Jane Doe");
57: echo "<p>New name is: " . $anAddress->getName() . "</p>\n";
58:
59: $anAddress->display();
60: ?>
61:</body>
62:</html>
Lines 10 - 13 defines the constructor for the class. With PHP, only one constructor can be defined per class. Notice that members of an object are accessed using the this
keyword. Values are passed in when the object is created and then assigned to the member variables using this
. Object methods and members are identified using "->
" the arrow operator, not dots like Ruby or Java.
Lines 16-22 defines a display method to output the contents of the class. Notice the this
keyword is used to access member variables.
Lines 24 - 38 define the standard getter and setter methods to access the member variables.
Lines 50-60 show the actual object in use. An object is created and immediately output. The name
member is changed, and then the object is output again.
Full Address Object
The previous sample was only a partial address object. The following example is a complete Address
object. Member variables have been added for city, state, and zip. In addition, a complete set of getters and setters has been added. The object is extended to demonstrate additional PHP object features.
Demo: object01b.php
Source: object01b.php
1:<?php
2:error_reporting(E_ALL);
3:
4:class Address{
5: // Members
6: private $name = '';
7: private $street = '';
8: private $city = '';
9: private $state = '';
10: private $zip = '';
11:
12: // Methods
13: function __construct($newName, $newStreet, $newCity, $newState, $newZip){
14: $this->name = $newName;
15: $this->street = $newStreet;
16: $this->city = $newCity;
17: $this->state = $newState;
18: $this->zip = $newZip;
19: }
20:
21:
22: public function display(){
23: echo "<h4>Address Entry</h4>\n";
24: echo "<p>\n";
25: echo "<b>Name: </b>" . $this->name . "<br/>\n";
26: echo "<b>Street: </b>" . $this->street . "<br/>\n";
27: echo "<b>City: </b>" . $this->city . "<br/>\n";
28: echo "<b>State: </b>" . $this->state . "<br/>\n";
29: echo "<b>Zip: </b>" . $this->zip . "<br/>\n";
30: echo "</p>\n";
31: }
32:
33: public function getName(){
34: return $this->name;
35: }
36:
37: public function setName($newName){
38: $this->name = $newName;
39: }
40:
41: public function getStreet(){
42: return $this->street;
43: }
44:
45: public function setStreet($newStreet){
46: $this->street = $newStreet;
47: }
48:
49: public function getCity(){
50: return $this->city;
51: }
52:
53: public function setCity($newCity){
54: $this->city = $newCity;
55: }
56:
57: public function getState(){
58: return $this->state;
59: }
60:
61: public function setState($newState){
62: $this->state = $newState;
63: }
64:
65: public function getZip(){
66: return $this->zip;
67: }
68:
69: public function setZip($newZip){
70: $this->zip = $newZip;
71: }
72:}
73:
74:?>
75:<html>
76:<head>
77: <title>PHP Address Object</title>
78:</head>
79:<body>
80: <h2>PHP Address Object</h2>
81: <p>Create an object and display it.</p>
82: <?php
83: $anAddress = new Address("John Doe", "1234 1st St", "New York", "NY", "12345");
84: $anAddress->display();
85: ?>
86: <p>Change the object contents and display them.</p>
87: <?php
88: $anAddress->setName("Jane Doe");
89: echo "<p>New name is: " . $anAddress->getName() . "</p>\n";
90:
91: $anAddress->setCity("Los Angeles");
92: echo "<p>New city is: " . $anAddress->getCity() . "</p>\n";
93:
94: $anAddress->setState("CA");
95: echo "<p>New state is: " . $anAddress->getState() . "</p>\n";
96:
97: $anAddress->display();
98: ?>
99:</body>
100:</html>
PHP 5 Overloading
The previous example demonstrates how tedious it can be to code an object. Many IDE's exist to make the repetitive coding of getters and setters easier. In PHP 5, this sort of coding is made easier through the use of "overloading". Now in a language like Java, "overloading" is the ability to define multiple signatures for a single method. In PHP 5, overloading is accomplished through the use of special methods like __get
, __set
, and __call
. The following example shows how the special __call
method can be used to replace all the getters and setters from the previous example. (See the PHP documention for more on __get and __set).
Demo: object02.php
Source: object02.php
1:<?php
2:error_reporting(E_ALL);
3:
4:class Address{
5: // Members
6: private $name = '';
7: private $street = '';
8: private $city = '';
9: private $state = '';
10: private $zip = '';
11:
12: // Methods
13: function __construct($newName, $newStreet, $newCity, $newState, $newZip){
14: $this->name = $newName;
15: $this->street = $newStreet;
16: $this->city = $newCity;
17: $this->state = $newState;
18: $this->zip = $newZip;
19: }
20:
21:
22: public function display(){
23: echo "<h4>Address Entry</h4>\n";
24: echo "<p>\n";
25: echo "<b>Name: </b>" . $this->name . "<br/>\n";
26: echo "<b>Street: </b>" . $this->street . "<br/>\n";
27: echo "<b>City: </b>" . $this->city . "<br/>\n";
28: echo "<b>State: </b>" . $this->state . "<br/>\n";
29: echo "<b>Zip: </b>" . $this->zip . "<br/>\n";
30: echo "</p>\n";
31: }
32:
33: function __call($method, $arguments) {
34: $prefix = strtolower(substr($method, 0, 3));
35: $property = strtolower(substr($method, 3));
36:
37: if (empty($prefix) || empty($property)) {
38: return;
39: }
40:
41: if ($prefix == "get" && isset($this->$property)) {
42: return $this->$property;
43: }
44:
45: if ($prefix == "set") {
46: $this->$property = $arguments[0];
47: }
48: }
49:
50:}
51:
52:?>
53:<html>
54:<head>
55: <title>PHP Address Object</title>
56:</head>
57:<body>
58: <h2>PHP Address Object</h2>
59: <p>Create an object and display it.</p>
60: <?php
61: $anAddress = new Address("John Doe", "1234 1st St", "New York", "NY", "12345");
62: $anAddress->display();
63: ?>
64: <p>Change the object contents and display them.</p>
65: <?php
66: $anAddress->setName("Jane Doe");
67: echo "<p>New name is: " . $anAddress->getName() . "</p>\n";
68:
69: $anAddress->setCity("Los Angeles");
70: echo "<p>New city is: " . $anAddress->getCity() . "</p>\n";
71:
72: $anAddress->setState("CA");
73: echo "<p>New state is: " . $anAddress->getState() . "</p>\n";
74:
75: $anAddress->display();
76: ?>
77:</body>
78:</html>
79:
Essentially, if an object method is called and is not recognized, the method request is forwarded to the __call
method. Lines 33-48 demonstrate code which performs all the functions of the previous getters and setters. When you run the script, you get the same output as you did before, with a lot less code.
Mutliple Constructor Signatures
Coming from a language like Java, where multiple signatures can be assigned to one constructor, The single constructor for PHP seems limiting. However, given PHP's dynamic nature, the same thing can be acheived by defining the method constructor arguments as an array. Then, different signatures can be passed and handled with the same method much like the __call
method. The following is a simplistic example of this.
Demo: object03.php
Source: object03.php
1 <?php
2 error_reporting(E_ALL);
3
4 class Address{
5 // Members
6 private $name = '';
7 private $street = '';
8 private $city = '';
9 private $state = '';
10 private $zip = '';
11
12 // Methods
13 function __construct(array $inArr){
14 $arrLength = count($inArr);
15
16 switch ($arrLength) {
17
18 case 3:
19 $this->name = $inArr[0];
20 $this->street = "";
21 $this->city = $inArr[1];
22 $this->state = $inArr[2];
23 $this->zip = "";
24 break;
25
26
27 case 5:
28 $this->name = $inArr[0];
29 $this->street = $inArr[1];
30 $this->city = $inArr[2];
31 $this->state = $inArr[3];
32 $this->zip = $inArr[4];
33 break;
34
35 default:
36 throw new Exception("$arrLength parameters not supported");
37 }
38 }
39
40
41 public function display(){
42 echo "<h4>Address Entry</h4>\n";
43 echo "<p>\n";
44 echo "<b>Name: </b>" . $this->name . "<br/>\n";
45 echo "<b>Street: </b>" . $this->street . "<br/>\n";
46 echo "<b>City: </b>" . $this->city . "<br/>\n";
47 echo "<b>State: </b>" . $this->state . "<br/>\n";
48 echo "<b>Zip: </b>" . $this->zip . "<br/>\n";
49 echo "</p>\n";
50 }
51
52 // Automatic Getters and Setters
53 function __call($method, $arguments) {
54 $prefix = strtolower(substr($method, 0, 3));
55 $property = strtolower(substr($method, 3));
56
57 if (empty($prefix) || empty($property)) {
58 return;
59 }
60
61 if ($prefix == "get" && isset($this->$property)) {
62 return $this->$property;
63 }
64
65 if ($prefix == "set") {
66 $this->$property = $arguments[0];
67 }
68 }
69
70 }
71 ?>
72 <html>
73 <head>
74 <title>PHP Address Object</title>
75 </head>
76 <body>
77 <h2>PHP Address Object</h2>
78 <p>Create an object and display it.</p>
79 <?php
80 $anAddress = new Address(array("John Doe", "1234 1st St", "New York", "NY", "12345"));
81 $anAddress->display();
82 ?>
83 <p>Change the object contents and display them.</p>
84 <?php
85 $anAddress->setName("Jane Doe");
86 echo "<p>New name is: " . $anAddress->getName() . "</p>\n";
87
88 $anAddress->setCity("Los Angeles");
89 echo "<p>New city is: " . $anAddress->getCity() . "</p>\n";
90
91 $anAddress->setState("CA");
92 echo "<p>New state is: " . $anAddress->getState() . "</p>\n";
93
94 $anAddress->display();
95 ?>
96 <?php
97 // Call with 3 params
98 $anAddress2 = new Address(array("John Doe", "New York", "NY"));
99 $anAddress2->display();
100
101 // This throws exception
102 /*
103 $anAddress2 = new Address(array("John Doe", "New York"));
104 $anAddress2->display();
105 */
106
107 ?>
108 </body>
109 </html>
Based on the number of arguments, the switch statement initializes the object accordingly. You could of course test of the kind of data passed, etc., and make the class definition much more complex.
Static Classes
Static classes are great for creating library functions when multiple object instances are not needed. The syntax and use of static classes is slightly different than regular objects.
The following example is a static class that encapsulates information about a database. Comments follow the code.
Demo: object04.php
Source: object04.php
1 <?php
2
3 // Class to store database information
4 class Object04 {
5 private static $hostname="dbhost.domain.com";
6 private static $port="1527";
7 private static $user="username";
8 private static $passwd="passwd";
9
10 public static function getHost(){
11 return self::$hostname;
12 }
13
14 public static function getPort(){
15 return self::$port;
16 }
17
18 public static function getUser(){
19 return self::$user;
20 }
21
22 public static function getPasswd(){
23 return self::$passwd;
24 }
25
26 public static function getURL(){
27 return "http://" . self::$hostname . ":" . self::$port;
28 }
29
30 }
31 ?>
32 <html>
33 <head>
34 <title>Object 04 Output</title>
35 </head>
36 <body>
37 <h4>DB Settings</h4>
38 <?php
39 echo "<p>Hostname: " . Object04::getHost() . "</p>";
40 echo "<p>Port: " . Object04::getPort() . "</p>";
41 echo "<p>URL: " . Object04::getURL() . "</p>";
42 ?>
43 </body>
44 </html>
Notice the use of the static
keyword to define class members and methods. Other than the static
keyword, the class and member definitions look pretty much the same as before.
Look at lines after the static class definition to see how the class is used. Notice that a double colon (::) is used to call class methods. Also note that dollar sign ($) does not precede the class name.
Static classes can be great for saving a lot of typing or having to remember all the possible ways to use a particular function.
That concludes the PHP object basics.