OOP Basics in PHP 5

Mar 30, 10 • PHP Tutorials4 CommentsRead More »

Introduction
PHP is a remarkable language, and Object Oriented Programming (OOP) is a remarkable concept. With object oriented design at the heart of PHP 5 and 6, developers can’t afford not to use it; it is a fundamental skill in increasing demand. This tutorial will introduce the basics of OOP in PHP5, and will show some of the major improvements from previous versions. We are just going over the basics, and will save the more advanced features for a future post.

Brief history of OOP in PHP
OOP in PHP hasn’t always been a core feature. In fact, when it made its first appearance it was more an afterthought than anything else. While primitive OOP support was added in PHP3, developers only started using it heavily in PHP4, where it started to gain real momentum. With that in mind, PHP 5 was designed with objects very much at the forefront of developers’ minds. What we now have is a system in place that permits the design of extremely complex systems through effective OOP designs.

Introduction to classes
Classes and objects are often interchanged, and thought of as being synonymous. Before anything else, we have to make a distinction between the two: classes are not objects, but are rather templates used to generate objects. The following class is not an object:

class Foo {
 // Class body
}

To generate an object instance using the Foo class as a template, we must use the new operator.

$Foo = new Foo();

Object properties
If you are familiar with PHP you should know how to use variables.

$FirstName = "Alex";
$SecondName = "Roxon";

Classes can also utilize member variables (or properties), which can be used to store and retrieve information relevant to the class. If you are familiar with classes in PHP4, you should recognize the following syntax:

class Foo {
 var $FirstName = "Alex";
 var $SecondName = "Roxon";
}

You would then access these properties via your $Foo object instance.

print( "My name is " . $Foo->FirstName . " " . $Foo->SecondName );

Which would output “My name is Alex Roxon”. While this practice is still acceptable, PHP 5 introduced the visibility keywords public, private and protected. The var keyword is identical to public, however if you are using PHP 5 you should use public, as there is no real point writing for backward compatibility. A common problem with objects in PHP 4, was that all properties were inherently public. This meant that individuals using your classes were directly able to alter any property outside of the class itself, which would often lead to disastrous errors. Let’s look at the following PHP 4 example.

class Foo {

 var $Version = 3;

 function VerCheck() {
     if($this->Version < 3) {
         die("You need version 3 to run.");
     }
 }

}

In itself, this class would perform as it was designed to: if the version property was less than three, the script would error, however as it isn’t, it should be fine. Errors can arise when fellow programmers unwittingly or erroneously alter these properties. For instance:

$Foo = new Foo();
$Foo->Version = 'abc';
$Foo->VerCheck();

The above would cause the error message “You need version 3 to run”, even though they may have the most up-to-date class. You can see then, where problems may arise. Thankfully, PHP5 allows us to solve this issue through these visibility keywords;

Public – this keyword specifies that a property may be accessed from any context. It doesn’t matter if you are outside of the class or in a child class, you always have complete control over public properties.

Private – from one extreme to another, private properties may only be accessed from the class itself – even child classes do not have access. Private properties are important should you not want users unnecessarily altering particular properties in your class.

Protected – protected properties may be accessed from the class it is declared in, as well as all child classes.

Methods

Methods are special functions declared within a class that allow your object to perform certain tasks. Just like a function declaration, a method is structured as so:

public function ClassMethod() {
    // Perform tasks here
}

Again, you are able to substitute public with either private or protected, according to the context in which you want your method called. You must remember though, that PHP 4 does not recognize visibility keywords, and by default your method is implicitly public.

To call your method, normally you will want to use the object variable, as well as -> followed by the method name. For example:

$Foo->ClassMethod();

Passing variables through to your method

This is the same as PHP 4 or any other function, just include the values to pass through in the method parentheses. For example:

public function ClassMethod($Name) {
    return "My name is " . $Name;
}

And calling it:

print $Foo->ClassMethod("Alex Roxon");

Which would output “My name is Alex Roxon”.

Constructor methods

A constructor method is called as soon as an object is first initiated. Let’s give a small example. We are going to create a small guess-the-number class. Without a constructor method, our class may look like this:

class NumberGuess {
    private $Number;

    public function chooseNumber() {
        $this->Number = rand(1,10);
    }

    public function guessNumber($Number) {
        if($this->Number == $Number) {
            print "You guessed correct!";
        } else {
            print "You guessed wrong.";
        }
    }
}

In this case, the chooseNumber() method would randomly generate a number between 1-10, and the guessNumber() method would check whether our guess matches the randomly generated number. An example of us utilizing this function would be:

$Guess = new NumberGuess();
$Guess->chooseNumber();
$Guess->guessNumber(5);

As you should see, whenever we want to use this class and play this game, the chooseNumber() method must always be called after we have initialized the new object. Since it must be called every time, always typing it out seems a bit unnecessary. This is where a constructor method would come in handy! Instead, we could rewrite our class as:

class NumberGuess {
    private $Number;

    public function __construct() {
        $this->Number = rand(1,10);
    }

    public function guessNumber($Number) {
        if($this->Number == $Number) {
            print "You guessed correct!";
        } else {
            print "You guessed wrong.";
        }
    }
}

And call it by:

$Guess = new NumberGuess();
$Guess->guessNumber(5);

The __construct() method is called automatically as the object is initialized. Which means, as soon as we initialize it the class randomly generates a number between 1-10. We no longer have to type it all out! Constructor classes are very useful, and you’ll find yourself using them a lot.

Note: although the __construct() method is exclusive to PHP 5, you could still achieve the same effect in PHP 4, by declaring a method with the same name as the class name. For instance, a PHP friendly version of the above class would become:

class NumberGuess {
    var $Number;

    function NumberGuess() {
        $this->Number = rand(1,10);
    }

    function guessNumber($Number) {
        if($this->Number == $Number) {
            print "You guessed correct!";
        } else {
            print "You guessed wrong.";
        }
    }
}

Again, like the visibility keywords, you should use start using __construct() if you are not already doing so.

Conclusion

OOP programming in PHP is forever gaining momentum. Like anything in life, fighting change will yield no positive reward. It is better to adapt to change so as to remain competitive and on par with the rest of the world. Programming is no different.

This tutorial has been relatively basic. The next in this series will explore object inheritance, static methods/properties, abstract classes, constants, in addition to some new special methods exclusive to PHP 5.

Comments are closed.