Object-Oriented PHP for Beginners
Tutorial Details
- Program : PHP
- Version (if applicable) : PHP 5+
- Difficulty: Intermediate
- Estimated Completion Time: 2 Hours
“For added control over objects, methods and properties are assigned visibility.”
Note — Visibility is a new feature as of PHP 5. For information on OOP compatibility with PHP 4 , see the PHP manual page.
Public Properties and Methods
All the methods and properties you’ve used so far have been public. This means that they can be accessed anywhere, both within the class and externally.
Protected Properties and Methods
When a property or method is declared protected , it can only be accessed within the class itself or in descendant classes (classes that extend the class containing the protected method).
Declare the getProperty() method as protected in MyClass and try to access it directly from outside the class:
- <?php
- class MyClass
- {
- public $prop1 = "I'm a class property!" ;
- public function __construct()
- {
- echo 'The class "', __CLASS__, '" was initiated!<br /> ';
- }
- public function __destruct()
- {
- echo ' The class "', __CLASS__, '" was destroyed.<br />';
- }
- public function __toString()
- {
- echo "Using the toString method: " ;
- return $this ->getProperty();
- }
- public function setProperty( $newval )
- {
- $this ->prop1 = $newval ;
- }
- protected function getProperty()
- {
- return $this ->prop1 . "<br />" ;
- }
- }
- class MyOtherClass extends MyClass
- {
- public function __construct()
- {
- parent::__construct();
- echo "A new constructor in " . __CLASS__ . ".<br />" ;
- }
- public function newMethod()
- {
- echo "From a new method in " . __CLASS__ . ".<br />" ;
- }
- }
- // Create a new object
- $newobj = new MyOtherClass;
- // Attempt to call a protected method
- echo $newobj ->getProperty();
- ?>
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
protected function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}
// Create a new object
$newobj = new MyOtherClass;
// Attempt to call a protected method
echo $newobj->getProperty();
?>
Upon attempting to run this script, the following error shows up:
- The class "MyClass" was initiated!
- A new constructor in MyOtherClass.
- Fatal error: Call to protected method MyClass::getProperty() from context '' in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 55
The class "MyClass" was initiated!
A new constructor in MyOtherClass.
Fatal error: Call to protected method MyClass::getProperty() from context '' in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 55
Now, create a new method in MyOtherClass to call the getProperty() method:
- <?php
- class MyClass
- {
- public $prop1 = "I'm a class property!" ;
- public function __construct()
- {
- echo 'The class "', __CLASS__, '" was initiated!<br /> ';
- }
- public function __destruct()
- {
- echo ' The class "', __CLASS__, '" was destroyed.<br />';
- }
- public function __toString()
- {
- echo "Using the toString method: " ;
- return $this ->getProperty();
- }
- public function setProperty( $newval )
- {
- $this ->prop1 = $newval ;
- }
- protected function getProperty()
- {
- return $this ->prop1 . "<br />" ;
- }
- }
- class MyOtherClass extends MyClass
- {
- public function __construct()
- {
- parent::__construct();
- echo "A new constructor in " . __CLASS__ . ".<br />" ;
- }
- public function newMethod()
- {
- echo "From a new method in " . __CLASS__ . ".<br />" ;
- }
- public function callProtected()
- {
- return $this ->getProperty();
- }
- }
- // Create a new object
- $newobj = new MyOtherClass;
- // Call the protected method from within a public method
- echo $newobj ->callProtected();
- ?>
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
protected function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
public function callProtected()
{
return $this->getProperty();
}
}
// Create a new object
$newobj = new MyOtherClass;
// Call the protected method from within a public method
echo $newobj->callProtected();
?>
This generates the desired result:
- The class "MyClass" was initiated!
- A new constructor in MyOtherClass.
- I'm a class property!
- The class "MyClass" was destroyed.
The class "MyClass" was initiated!
A new constructor in MyOtherClass.
I'm a class property!
The class "MyClass" was destroyed.
Private Properties and Methods
A property or method declared private is accessible only from within the class that defines it . This means that even if a new class extends the class that defines a private property, that property or method will not be available at all within the child class.
To demonstrate this, declare getProperty() as private in MyClass , and attempt to call callProtected() from
MyOtherClass :
- <?php
- class MyClass
- {
- public $prop1 = "I'm a class property!" ;
- public function __construct()
- {
- echo 'The class "', __CLASS__, '" was initiated!<br /> ';
- }
- public function __destruct()
- {
- echo ' The class "', __CLASS__, '" was destroyed.<br />';
- }
- public function __toString()
- {
- echo "Using the toString method: " ;
- return $this ->getProperty();
- }
- public function setProperty( $newval )
- {
- $this ->prop1 = $newval ;
- }
- private function getProperty()
- {
- return $this ->prop1 . "<br />" ;
- }
- }
- class MyOtherClass extends MyClass
- {
- public function __construct()
- {
- parent::__construct();
- echo "A new constructor in " . __CLASS__ . ".<br />" ;
- }
- public function newMethod()
- {
- echo "From a new method in " . __CLASS__ . ".<br />" ;
- }
- public function callProtected()
- {
- return $this ->getProperty();
- }
- }
- // Create a new object
- $newobj = new MyOtherClass;
- // Use a method from the parent class
- echo $newobj ->callProtected();
- ?>
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
private function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
public function callProtected()
{
return $this->getProperty();
}
}
// Create a new object
$newobj = new MyOtherClass;
// Use a method from the parent class
echo $newobj->callProtected();
?>
Reload your browser, and the following error appears:
- The class "MyClass" was initiated!
- A new constructor in MyOtherClass.
- Fatal error: Call to private method MyClass::getProperty() from context 'MyOtherClass' in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 49
The class "MyClass" was initiated!
A new constructor in MyOtherClass.
Fatal error: Call to private method MyClass::getProperty() from context 'MyOtherClass' in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 49
Static Properties and Methods
A method or property declared static can be accessed without first instantiating the class; you simply supply the class name, scope resolution operator, and the property or method name.
“One of the major benefits to using static properties is that they keep their stored values for the duration of the script.”
To demonstrate this, add a static property called $count and a static method called plusOne() to MyClass . Then set up a do...while loop to output the incremented value of $count as long as the value is less than 10:
- <?php
- class MyClass
- {
- public $prop1 = "I'm a class property!" ;
- public static $count = 0;
- public function __construct()
- {
- echo 'The class "', __CLASS__, '" was initiated!<br /> ';
- }
- public function __destruct()
- {
- echo ' The class "', __CLASS__, '" was destroyed.<br />';
- }
- public function __toString()
- {
- echo "Using the toString method: " ;
- return $this ->getProperty();
- }
- public function setProperty( $newval )
- {
- $this ->prop1 = $newval ;
- }
- private function getProperty()
- {
- return $this ->prop1 . "<br />" ;
- }
- public static function plusOne()
- {
- return "The count is " . ++self:: $count . ".<br />" ;
- }
- }
- class MyOtherClass extends MyClass
- {
- public function __construct()
- {
- parent::__construct();
- echo "A new constructor in " . __CLASS__ . ".<br />" ;
- }
- public function newMethod()
- {
- echo "From a new method in " . __CLASS__ . ".<br />" ;
- }
- public function callProtected()
- {
- return $this ->getProperty();
- }
- }
- do
- {
- // Call plusOne without instantiating MyClass
- echo MyClass::plusOne();
- } while ( MyClass:: $count < 10 );
- ?>
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public static $count = 0;
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
private function getProperty()
{
return $this->prop1 . "<br />";
}
public static function plusOne()
{
return "The count is " . ++self::$count . ".<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
public function callProtected()
{
return $this->getProperty();
}
}
do
{
// Call plusOne without instantiating MyClass
echo MyClass::plusOne();
} while ( MyClass::$count < 10 );
?>
Note — When accessing static properties, the dollar sign
($ ) comes after the scope resolution operator.
When you load this script in your browser, the following is output:
- The count is 1.
- The count is 2.
- The count is 3.
- The count is 4.
- The count is 5.
- The count is 6.
- The count is 7.
- The count is 8.
- The count is 9.
- The count is 10.
The count is 1.
The count is 2.
The count is 3.
The count is 4.
The count is 5.
The count is 6.
The count is 7.
The count is 8.
The count is 9.
The count is 10.
Commenting with DocBlocks
“The DocBlock commenting style is a widely
accepted method of documenting classes.”
While not an official part of OOP, the DocBlock commenting style is a widely accepted method of documenting classes. Aside from providing a standard for
developers to use when writing code, it has also been adopted by many of the most popular software development kits (SDKs), such as Eclipse and NetBeans , and will be used to generate code hints.
A DocBlock is defined by using a block comment that starts with an additional asterisk:
- /**
- * This is a very basic DocBlock
- */
/**
* This is a very basic DocBlock
*/
The real power of DocBlocks comes with the ability to use tags , which start with an at symbol (@ ) immediately followed by the tag name and the value of the tag. DocBlock tags allow developers to define authors of a file, the license for a class, the property or method information, and other useful information.
The most common tags used follow:
- @author : The author of the current element (which might be a class, file, method, or any bit of code) are listed using this tag. Multiple author tags can be used in the same DocBlock if more than one author is credited. The format for the author name is John Doe <john.doe@email.com> .
- @copyright : This signifies the copyright year and name of the copyright holder for the current element. The format is 2010 Copyright Holder .
- @license : This links to the license for the current element. The format for the license information is
http://www.example.com/path/to/license.txt License Name . - @var : This holds the type and description of a variable or class property. The format is type element description .
- @param : This tag shows the type and description of a function or method parameter. The format is type $element_name element description .
- @return : The type and description of the return value of a function or method are provided in this tag. The format is type return element description .
A sample class commented with DocBlocks might look like this:
- <?php
- /**
- * A simple class
- *
- * This is the long description for this class,
- * which can span as many lines as needed. It is
- * not required, whereas the short description is
- * necessary.
- *
- * It can also span multiple paragraphs if the
- * description merits that much verbiage.
- *
- * @author Jason Lengstorf <jason.lengstorf@ennuidesign.com>
- * @copyright 2010 Ennui Design
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- */
- class SimpleClass
- {
- /**
- * A public variable
- *
- * @var string stores data for the class
- */
- public $foo ;
- /**
- * Sets $foo to a new value upon class instantiation
- *
- * @param string $val a value required for the class
- * @return void
- */
- public function __construct( $val )
- {
- $this ->foo = $val ;
- }
- /**
- * Multiplies two integers
- *
- * Accepts a pair of integers and returns the
- * product of the two.
- *
- * @param int $bat a number to be multiplied
- * @param int $baz a number to be multiplied
- * @return int the product of the two parameters
- */
- public function bar( $bat , $baz )
- {
- return $bat * $baz ;
- }
- }
- ?>
<?php
/**
* A simple class
*
* This is the long description for this class,
* which can span as many lines as needed. It is
* not required, whereas the short description is
* necessary.
*
* It can also span multiple paragraphs if the
* description merits that much verbiage.
*
* @author Jason Lengstorf <jason.lengstorf@ennuidesign.com>
* @copyright 2010 Ennui Design
* @license http://www.php.net/license/3_01.txt PHP License 3.01
*/
class SimpleClass
{
/**
* A public variable
*
* @var string stores data for the class
*/
public $foo;
/**
* Sets $foo to a new value upon class instantiation
*
* @param string $val a value required for the class
* @return void
*/
public function __construct($val)
{
$this->foo = $val;
}
/**
* Multiplies two integers
*
* Accepts a pair of integers and returns the
* product of the two.
*
* @param int $bat a number to be multiplied
* @param int $baz a number to be multiplied
* @return int the product of the two parameters
*/
public function bar($bat, $baz)
{
return $bat * $baz;
}
}
?>
Once you scan the preceding class, the benefits of DocBlock are apparent: everything is clearly defined so that the next developer can pick up the code and never have to wonder what a snippet of code does or what it should contain.
Comparing Object-Oriented and Procedural Code
There’s not really a right and wrong way to write code. That being said, this section outlines a strong argument for adopting an object-oriented approach in software development, especially in large applications.
Reason 1: Ease of Implementation
“While it may be daunting at first, OOP actually provides an easier approach to dealing with data.”
While it may be daunting at first, OOP actually provides an easier approach to dealing with data. Because an object can store data internally, variables don’t need to be passed from function to function to work properly.
Also, because multiple instances of the same class can exist simultaneously , dealing with large data sets is infinitely easier. For instance, imagine you have two people’s information being processed in a file. They need names, occupations, and ages.
The Procedural Approach
Here’s the procedural approach to our example:
- <?php
- function changeJob( $person , $newjob )
- {
- $person [ 'job' ] = $newjob ; // Change the person's job
- return $person ;
- }
- function happyBirthday( $person )
- {
- ++$person ['age ']; // Add 1 to the person' s age
- return $person ;
- }
- $person1 = array (
- 'name' => 'Tom' ,
- 'job' => 'Button-Pusher' ,
- 'age' => 34
- );
- $person2 = array (
- 'name' => 'John' ,
- 'job' => 'Lever-Puller' ,
- 'age' => 41
- );
- // Output the starting values for the people
- echo "<pre>Person 1: " , print_r( $person1 , TRUE), "</pre>" ;
- echo "<pre>Person 2: " , print_r( $person2 , TRUE), "</pre>" ;
- // Tom got a promotion and had a birthday
- $person1 = changeJob( $person1 , 'Box-Mover' );
- $person1 = happyBirthday( $person1 );
- // John just had a birthday
- $person2 = happyBirthday( $person2 );
- // Output the new values for the people
- echo "<pre>Person 1: " , print_r( $person1 , TRUE), "</pre>" ;
- echo "<pre>Person 2: " , print_r( $person2 , TRUE), "</pre>" ;
- ?>
<?php
function changeJob($person, $newjob)
{
$person['job'] = $newjob; // Change the person's job
return $person;
}
function happyBirthday($person)
{
++$person['age']; // Add 1 to the person's age
return $person;
}
$person1 = array(
'name' => 'Tom',
'job' => 'Button-Pusher',
'age' => 34
);
$person2 = array(
'name' => 'John',
'job' => 'Lever-Puller',
'age' => 41
);
// Output the starting values for the people
echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
// Tom got a promotion and had a birthday
$person1 = changeJob($person1, 'Box-Mover');
$person1 = happyBirthday($person1);
// John just had a birthday
$person2 = happyBirthday($person2);
// Output the new values for the people
echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
?>
When executed, the code outputs the following:
- Person 1: Array
- (
- [name] => Tom
- [job] => Button-Pusher
- [age] => 34
- )
- Person 2: Array
- (
- [name] => John
- [job] => Lever-Puller
- [age] => 41
- )
- Person 1: Array
- (
- [name] => Tom
- [job] => Box-Mover
- [age] => 35
- )
- Person 2: Array
- (
- [name] => John
- [job] => Lever-Puller
- [age] => 42
- )
Person 1: Array
(
[name] => Tom
[job] => Button-Pusher
[age] => 34
)
Person 2: Array
(
[name] => John
[job] => Lever-Puller
[age] => 41
)
Person 1: Array
(
[name] => Tom
[job] => Box-Mover
[age] => 35
)
Person 2: Array
(
[name] => John
[job] => Lever-Puller
[age] => 42
)
While this code isn’t necessarily bad, there’s a lot to keep in mind while coding. The array of the affected person’s attributes must be passed and returned from each function call , which leaves margin for error.
To clean up this example, it would be desirable to leave as few things up to the developer as possible. Only absolutely essential information for the current operation should need to be passed to the functions.
This is where OOP steps in and helps you clean things up.
The OOP Approach
Here’s the OOP approach to our example:
- <?php
- class Person
- {
- private $_name ;
- private $_job ;
- private $_age ;
- public function __construct( $name , $job , $age )
- {
- $this ->_name = $name ;
- $this ->_job = $job ;
- $this ->_age = $age ;
- }
- public function changeJob( $newjob )
- {
- $this ->_job = $newjob ;
- }
- public function happyBirthday()
- {
- ++$this ->_age;
- }
- }
- // Create two new people
- $person1 = new Person( "Tom" , "Button-Pusher" , 34);
- $person2 = new Person( "John" , "Lever Puller" , 41);
- // Output their starting point
- echo "<pre>Person 1: " , print_r( $person1 , TRUE), "</pre>" ;
- echo "<pre>Person 2: " , print_r( $person2 , TRUE), "</pre>" ;
- // Give Tom a promotion and a birthday
- $person1 ->changeJob( "Box-Mover" );
- $person1 ->happyBirthday();
- // John just gets a year older
- $person2 ->happyBirthday();
- // Output the ending values
- echo "<pre>Person 1: " , print_r( $person1 , TRUE), "</pre>" ;
- echo "<pre>Person 2: " , print_r( $person2 , TRUE), "</pre>" ;
- ?>
<?php
class Person
{
private $_name;
private $_job;
private $_age;
public function __construct($name, $job, $age)
{
$this->_name = $name;
$this->_job = $job;
$this->_age = $age;
}
public function changeJob($newjob)
{
$this->_job = $newjob;
}
public function happyBirthday()
{
++$this->_age;
}
}
// Create two new people
$person1 = new Person("Tom", "Button-Pusher", 34);
$person2 = new Person("John", "Lever Puller", 41);
// Output their starting point
echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
// Give Tom a promotion and a birthday
$person1->changeJob("Box-Mover");
$person1->happyBirthday();
// John just gets a year older
$person2->happyBirthday();
// Output the ending values
echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
?>
This outputs the following in the browser:
- Person 1: Person Object
- (
- [_name:private ] => Tom
- [_job:private ] => Button-Pusher
- [_age:private ] => 34
- )
- Person 2: Person Object
- (
- [_name:private ] => John
- [_job:private ] => Lever Puller
- [_age:private ] => 41
- )
- Person 1: Person Object
- (
- [_name:private ] => Tom
- [_job:private ] => Box-Mover
- [_age:private ] => 35
- )
- Person 2: Person Object
- (
- [_name:private ] => John
- [_job:private ] => Lever Puller
- [_age:private ] => 42
- )
Person 1: Person Object
(
[_name:private] => Tom
[_job:private] => Button-Pusher
[_age:private] => 34
)
Person 2: Person Object
(
[_name:private] => John
[_job:private] => Lever Puller
[_age:private] => 41
)
Person 1: Person Object
(
[_name:private] => Tom
[_job:private] => Box-Mover
[_age:private] => 35
)
Person 2: Person Object
(
[_name:private] => John
[_job:private] => Lever Puller
[_age:private] => 42
)
There’s a little bit more setup involved to make the approach object oriented, but after the class is defined, creating and modifying people is a breeze; a person’s information does not need to be passed or returned from methods, and only absolutely essential information is passed to each method.
“OOP will significantly reduce your workload if implemented properly.”
On the small scale, this difference may not seem like much, but as your applications grow in size, OOP will significantly reduce your workload if implemented properly.
Tip — Not everything needs to be object oriented. A quick function that handles something small in one place inside the application does not necessarily need to be wrapped in a class. Use your best judgment when deciding between object-oriented and procedural approaches.
Reason 2: Better Organization
Another benefit of OOP is how well it lends itself to being easily packaged and cataloged. Each class can generally be kept in its own separate file, and if a uniform naming convention is used, accessing the classes is extremely simple.
Assume you’ve got an application with 150 classes that are called dynamically through a controller file at the root of your application filesystem. All 150 classes follow the naming convention class.classname.inc.php and reside in the inc folder of your application.
The controller can implement PHP’s __autoload() function to dynamically pull in only the classes it needs as they are called, rather than including all 150 in the controller file just in case or coming up with some clever way of including the files in your own code:
- <?php
- function __autoload( $class_name )
- {
- include_once 'inc/class.' . $class_name . '.inc.php' ;
- }
- ?>
<?php
function __autoload($class_name)
{
include_once 'inc/class.' . $class_name . '.inc.php';
}
?>
Having each class in a separate file also makes code more portable and easier to reuse in new applications without a bunch of copying and pasting.
Reason 3: Easier Maintenance
Due to the more compact nature of OOP when done correctly, changes in the code are usually much easier to spot and make than in a long spaghetti code procedural implementation.
If a particular array of information gains a new attribute, a procedural piece of software may require (in a worst-case scenario) that the new attribute be added to each function that uses the array.
An OOP application could potentially be updated as easily adding the new property and then adding the methods that deal with said property.
A lot of the benefits covered in this section are the product of OOP in combination with DRY programming practices. It is definitely possible to create easy-to-maintain procedural code that doesn’t cause nightmares, and it is equally possible to create awful object-oriented code. [Pro PHP and jQuery ] will attempt to demonstrate a combination of good coding habits in conjunction with OOP to generate clean code that’s easy to read and maintain.
Summary
At this point, you should feel comfortable with the object-oriented programming style. Learning OOP is a great way to take your programming to that next level. When implemented properly, OOP will help you produce easy-to-read, easy-to-maintain, portable code that will save you (and the developers who work with you) hours of extra work. Are you stuck on something that wasn’t covered in this article? Are you already using OOP and have some tips for beginners? Share them in the comments!