Category Archives: PHP

OOP & PHP5

Since the introduction of PHP 5 in 2004, PHP has had an object model worthy of that description and became a truly modern language for use on the web. Earlier PHP scripts would have been of the kind where, to quote from Alice’s Adventures, you would “Begin at the beginning, and go on till you come to the end: then stop.”

Nowadays that very procedural approach is less common in PHP, so this article takes a look at some of the basic object oriented features available in the language and shows some examples of using them with code examples.

Using OOP (Object Orientated Programming) enables us to architect our systems much more clearly, and to make them more manageable and more maintainable. This technique also allows us to separate form from function to create clean, navigable codebases with plenty of opportunities to reuse code, apply design patterns and bring in concepts from other brances of computer science.

Objects vs Classes
While the terms “object” and “class” are often used almost interchangeably in the world of software, there is a definite conceptual difference between the two. A class is the blueprint or recipe; it describes what the object should be, have and do. So a class might look like this:

<br />
class Elephpant {<br />
    public $colour;</p>
<p>    public function dance() {<br />
        echo &amp;quot;elephpant dances!\n&amp;quot;;<br />
        return true;<br />
    }<br />
}<br />

elephpant.php

An object, on the other hand, is an actual instantiation of the class – its an actual thing, with values and behaviours. In the example below, $ele is the object:

<br />
include('elephpant.php');</p>
<p>$ele = new Elephpant();<br />

We can inspect $ele to make sure that it is, in fact, an object of the class Elephpant, using the print_r command. Adding this to our code sample as shown, we see the output below:

<br />
include('elephpant.php');</p>
<p>$ele = new Elephpant();<br />
print_r($ele);</p>
<p>Elephpant Object<br />
(<br />
    [colour] =&amp;gt;<br />
)<br />

This output shows an object, of type Elephpant, and with a single empty property named “colour”. For more information about the objects exact properties and their values, you can also use var_dump, which gives a more detailed output showing in detail the datatypes of each property. This is particularly useful for spotting empty strings, nulls and false.

Using Objects, Their Properties and Methods

Our class, Elephpant, has a property and a method (OO-speak for “function”) already defined inside it, so how can we interact with these? Let’s start by setting the colour property; we use the object operator which is a hyphen followed by a greater than sign.

<br />
include('elephpant.php');</p>
<p>$ele = new Elephpant();</p>
<p>// set the colour property<br />
$ele-&amp;gt;colour = &amp;quot;blue&amp;quot;;</p>
<p>// now use that property<br />
echo &amp;quot;The elephpant is &amp;quot; . $ele-&amp;gt;colour;<br />

The output of this script reads “The elephpant is blue”. The property will remain set on the object until the object is destroyed, or the property overwritten or unset. Objects are a great way of keeping things together that belong together, for example information about an elephpant!

Similarly we can call the method using the same operator – the brackets after the call let PHP know its a method rather than a property, and if we had parameters to pass in they’d go between the brackets. Something like this:

<br />
include('elephpant.php');</p>
<p>$ele = new Elephpant();</p>
<p>// call the dance method<br />
$ele-&amp;gt;dance();<br />

Look back at the class declaration for Elephpant and you’ll see the dance method actually echoes from within it. Indeed when we run the code example here, we see “elephpant dances!” as our output. It is a very trivial example but I hope it does show how to call methods against our objects. An alternative approach (and probably a better one within an actual application) would be to create the string and use it as the return value for the function. Then the calling code can take the string and echo it, or do whatever else it needs to, in a more flexible way.

Inheritance

Now we know how to create and interact with objects, let’s step things up a bit and look at how we can create objects which are similar in some ways and different in others, using inheritance. If you are accustomed to OOP from any other programming languages then this will seem very familiar to you, so here is a quick look at how this can be done in PHP. We already have our Elephpant class declared, so let’s add a Penguin class as well. They will both inherit from the parent class Animal, which looks like this:

<br />
class Animal{</p>
<p>    public $type = &amp;quot;animal&amp;quot;;</p>
<p>    public function dance() {<br />
        echo $this-&amp;gt;type . &amp;quot; dances!\n&amp;quot;;<br />
        return true;<br />
    }<br />
}<br />

animal.php

The animal has a “type” property, and a dance() method. It uses the type property in the dance() method to create the output, using $this to refer to the current object. In PHP, $this is a special keyword which refers to the current object from within its own class.
Now we can create a Penguin class that inherits from this general Animal class, by using the extends keyword to denote its parent:

<br />
class Penguin extends Animal {<br />
    public $type = &amp;quot;penguin&amp;quot;;<br />
}<br />

penguin.php

The penguin class would inherit the type property set to “animal” if we didn’t override it by setting the property again in this class. However even without declaring a dance() method, the penguin can dance!

<br />
include('animal.php');<br />
include('penguin.php');</p>
<p>$tux = new Penguin();</p>
<p>// make tux dance<br />
$tux-&amp;gt;dance();<br />

The above example gives the output “penguin dances!” – using the dance() method from the Animal class, which is available because the Penguin class extends it, and the type property set separately in the Penguin class itself.

Access Modifiers

Take a look at the previous example. The type is set in the class, but we could easily set it from our main code if we wanted to. Imagine if we put $tux->type = “giraffe” before we asked him to dance! Sometimes this is the desired behavior, and sometimes it isn’t. To allow us to control whether properties can be changed outside a class, PHP gives us access modifiers. An example of these are the “public” keywords you see in the classes shown above. To prevent the type property being edited from outside the class, we can declare the Penguin type to be private, so the class now looks like this:

<br />
class Penguin extends Animal {<br />
    private $type = &amp;quot;penguin&amp;quot;;<br />
}<br />

private_penguin.php

The following code listing shows us trying to set the now-private type property, and is followed by the resulting output.

<br />
include('animal.php');<br />
include('private_penguin.php');</p>
<p>$tux = new Penguin();</p>
<p>// change the type<br />
$tux-&amp;gt;type = &amp;quot;linux penguin&amp;quot;;<br />
// make tux dance<br />
$tux-&amp;gt;dance();<br />

Fatal error: Access level to Penguin::$type must be public (as in class Animal) in /home/lorna/…/OOP/private_penguin.php on line 5

The resulting message feeds back to the user that the type property can’t be modified, and even includes the detail that the property was public in the parent class. Access modifiers are pretty powerful, we should look at them in more detail.

Access modifiers can be applied to properties and to methods and to properties. The options are public, private and protected. In PHP4, these weren’t available and everything is public. As a result, and to maintain backwards compatibility, if an access modifier isn’t specified then the property or method defaults to being public. This isn’t recommended practice however, and it is best to be explicit about which is intended.

Public: The public access modifier means that properties and methods can be accessed from anywhere, within the scope of the object itself, and also from outside code operating on an object.

Private: The method or property is only available from within the scope of this specific class. Before using this option, read on to find out about the “protected” access modifier.

Protected: The method or property is available from within this class, and from within any classes with extend or implement this class. This is ideal where you don’t want external code to change the class, but you do want to be able to extend the class later and take advantage of this property or method. Protected is more flexible than private and almost always the better choice.

Using these access modifiers we can control where our class methods and properties can be accessed from. We looked at an example of properties and this works in the same way for method calls – they cannot be accessed from outside of the class definition unless they are declared to be public. It can be very useful indeed to declare methods as protected, where they are internal helper methods used by other class methods but not intended to be accessed directly. In PHP4 there was no support for this and so the internal methods were sometimes named with an underscore to hint that this was their intended use – it is still possible to see this naming convention in use today, although it is not needed.

Using OOP in PHP: Practical Example

Object Oriented design is particularly useful where you have data objects that relate to one another – so it is very common for example to have OOP used to deal with data. PHP 5 has the PDO (PHP Data Object) classes which are a great way to talk to a backend database, either mysql or any other kind of database, and using the object oriented interface offered by this extension ties in well with the usage I have shown here.

A common mistake for those coming to OO for the first time is to declare methods inside a class but then instantiate a single copy of that and pass in data such as the ID of the data to each method. Here’s an example of a user class that does this:

<br />
class User {<br />
    /**<br />
     * getDisplayName<br />
     *<br />
     * @param int $user_id the user_id of the user in the database table<br />
     * @access public<br />
     * @return string Display name of this user<br />
     */<br />
    public function getDisplayName($user_id) {<br />
        $sql = 'select display_name from users where user_id = '.$user_id;<br />
        $results = mysql_query($sql);<br />
        $row = mysql_fetch_array($results);<br />
        return $row['display_name'];<br />
    }</p>
<p>    /**<br />
     * getFriends<br />
     *<br />
     * @param int $user_id the user_id of the user in the database table<br />
     * @access public<br />
     * @return array An array of friend_ids<br />
     */<br />
    public function getFriends($user_id) {<br />
        $sql = 'select friend_id from user_friends where user_id = '.$user_id;<br />
        $results = mysql_query($sql);<br />
        $friends = array();<br />
        while($row = mysql_fetch_array($results)) {<br />
            $friends[] = $row['friend_id'];<br />
        }<br />
        return $friends;<br />
    }<br />
}<br />

user.php

And some code that uses it:

<br />
include('user.php');<br />
mysql_connect('localhost','root','');<br />
mysql_select_db('test');</p>
<p>$user = new User();<br />
echo &amp;quot;User known as: &amp;quot; . $user-&amp;gt;getDisplayName(1) . &amp;quot;\n&amp;quot;;</p>
<p>$friends = $user-&amp;gt;getFriends(1);<br />
echo &amp;quot;Friends with: &amp;quot; . implode(', ',$friends) . &amp;quot;\n&amp;quot;;<br />

If you want to run this code yourself, then you can set up the database tables using this script:

<br />
CREATE TABLE `user_friends` (<br />
  `user_friend_id` int(11) NOT NULL AUTO_INCREMENT,<br />
  `user_id` int(11) NOT NULL,<br />
  `friend_id` int(11) NOT NULL,<br />
  PRIMARY KEY (`user_friend_id`)<br />
)<br />
INSERT INTO `user_friends` VALUES (1,1,3),(2,1,5);</p>
<p>CREATE TABLE `users` (<br />
  `user_id` int(11) NOT NULL AUTO_INCREMENT,<br />
  `first_name` varchar(20) DEFAULT NULL,<br />
  `last_name` varchar(50) DEFAULT NULL,<br />
  `display_name` varchar(50) DEFAULT NULL,<br />
  PRIMARY KEY (`user_id`)<br />
)<br />
INSERT INTO `users` VALUES (1,'Lorna','Mitchell','lornajane');<br />

user.sql

This is more like a function library than an actual object, and although it works perfectly well and does have its applications, it can be better to aim to take advantage of more object oriented features. To do this, a new object should be created for each item the system handles, and if it has an ID and perhaps some other properties, these should be set as part of the object. Then rather than creating a single user object and doing getFriends(42) on it, you’d have a user with ID 42 which did $user->getFriends().

Here’s a follow up example with a class and how to use it, this will give better performance and enable you to clearly see which data goes with which object where there are multiple items on a page:

<br />
class User {<br />
    /**<br />
     * getUserById<br />
     *<br />
     * @param int $user_id the id of the user row in the table<br />
     * @access public<br />
     * @return true if the user was found<br />
     */<br />
    public function getUserById($user_id) {<br />
        $sql = 'select first_name, last_name, display_name from users where user_id = ' . $user_id;<br />
        $results = mysql_query($sql);<br />
        $row = mysql_fetch_array($results);<br />
        $this-&amp;gt;user_id = $user_id;<br />
        $this-&amp;gt;first_name = $row['first_name'];<br />
        $this-&amp;gt;last_name = $row['last_name'];<br />
        $this-&amp;gt;display_name = $row['display_name'];</p>
<p>        // in real life, there would be escaping and error handling and we'd only return true if we got data<br />
        return true;<br />
    }</p>
<p>    /**<br />
     * getDisplayName<br />
     *<br />
     * @access public<br />
     * @return string Display name of this user<br />
     */<br />
    public function getDisplayName() {<br />
        return $this-&amp;gt;display_name;<br />
    }</p>
<p>    /**<br />
     * getFriends<br />
     *<br />
     * @access public<br />
     * @return array An array of friend_ids<br />
     */<br />
    public function getFriends() {<br />
        $sql = 'select friend_id from user_friends where user_id = '.$this-&amp;gt;user_id;<br />
        $results = mysql_query($sql);<br />
        $friends = array();<br />
        while($row = mysql_fetch_array($results)) {<br />
            $friends[] = $row['friend_id'];<br />
        }<br />
        return $friends;<br />
    }<br />
}<br />

user2.php

<br />
include('user2.php');<br />
mysql_connect('localhost','root','');<br />
mysql_select_db('test');</p>
<p>$user = new User();<br />
// populate the object<br />
$user-&amp;gt;getUserById(1);<br />
echo &amp;quot;User known as: &amp;quot; . $user-&amp;gt;getDisplayName() . &amp;quot;\n&amp;quot;;</p>
<p>$friends = $user-&amp;gt;getFriends();<br />
echo &amp;quot;Friends with: &amp;quot; . implode(', ',$friends) . &amp;quot;\n&amp;quot;;<br />

In Summary

This has been a very introductory look at some of the object oriented features available in PHP, to get you started out with the basics of working with OO code and also writing your own. If this has helped you take your first OOP steps, then let us know by leaving a comment and let us know what you built! In the next post there will be some more in-depth content including using constructors, access modifiers and working with the static keyword in PHP – taking your skills to the next level.

'Coz sharing is caring

9 Magic Methods for PHP

The “magic” methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events.

That might sound slightly automagical but actually it’s pretty straightforward, we already saw an example of this in the last post, where we used a constructor – so we’ll use this as our first example.

__construct

The constructor is a magic method that gets called when the object is instantiated. It is usually the first thing in the class declaration but it does not need to be, it is a method like any other and can be declared anywhere in the class.

Constructors also inherit like any other method. So if we consider our previous inheritance example from the Introduction to OOP, we could add a constructor to the Animal class like this:

<br />
class Animal {</p>
<p>  public function __construct() {<br />
    $this-&gt;created = time();<br />
    $this-&gt;logfile_handle = fopen('/tmp/log.txt', 'w');<br />
  }</p>
<p>}<br />

animal.php

Now we can create a class which inherits from the Animal class – a Penguin! Without adding anything into the Penguin class, we can declare it and have it inherit from Animal, like this:

<br />
class Penguin extends Animal {</p>
<p>}</p>
<p>$tux = new Penguin;<br />
echo $tux-&gt;created;<br />

If we define a __construct method in the Penguin class, then Penguin objects will run that instead when they are instantiated. Since there isn’t one, PHP looks to the parent class definition for information and uses that. So we can override, or not, in our new class – very handy.

__destruct

Did you spot the file handle that was also part of the constructor? We don’t really want to leave things like that lying around when we finish using an object and so the __destruct method does the opposite of the constructor. It gets run when the object is destroyed, either expressly by us or when we’re not using it any more and PHP cleans it up for us. For the Animal, our __destruct method might look something like this:

<br />
class Animal{</p>
<p>  public function __construct() {<br />
    $this-&gt;created = time();<br />
    $this-&gt;logfile_handle = fopen('/tmp/log.txt', 'w');<br />
  }</p>
<p>  public function __destruct() {<br />
    fclose($this-&gt;logfile_handle);<br />
  }<br />
}<br />

animal2.php

The destructor lets us close up any external resources that were being used by the object. In PHP since we have such short running scripts (and look out for greatly improved garbage collection in newer versions), often issues such as memory leaks aren’t a problem. However it’s good practice to clean up and will give you a more efficient application overall!

__get

This next magic method is a very neat little trick to use – it makes properties which actually don’t exist appear as if they do. Let’s take our little penguin:

<br />
class Penguin extends Animal {</p>
<p>  public function __construct($id) {<br />
    $this-&gt;getPenguinFromDb($id);<br />
  }</p>
<p>  public function getPenguinFromDb($id) {<br />
    // elegant and robust database code goes here<br />
  }<br />
}<br />

penguin1.php

Now if our penguin has the properties “name” and “age” after it is loaded, we’d be able to do:

<br />
$tux = new Penguin(3);<br />
echo $tux-&gt;name . &quot; is &quot; . $tux-&gt;age . &quot; years old\n&quot;;<br />

However imagine something changed about the backend database or information provider, so instead of “name”, the property was called “username”. And imagine this is a complex application which refers to the “name” property in too many places for us to change. We can use the __get method to pretend that the “name” property still exists:

<br />
class Penguin extends Animal {</p>
<p>  public function __construct($id) {<br />
    $this-&gt;getPenguinFromDb($id);<br />
  }</p>
<p>  public function getPenguinFromDb($id) {<br />
    // elegant and robust database code goes here<br />
  }</p>
<p>  public function __get($field) {<br />
    if($field == 'name') {<br />
      return $this-&gt;username;<br />
    }<br />
}<br />

penguin2.php

This technique isn’t really a good way to write whole systems, because it makes code hard to debug, but it is a very valuable tool. It can also be used to only load properties on demand or show calculated fields as properties, and a hundred other applications that I haven’t even thought of!

__set

So we updated all the calls to $this->name to return $this->username but what about when we want to set that value, perhaps we have an account screen where users can change their name? Help is at hand in the form of the __set method, and easiest to illustrate with an example.

<br />
class Penguin extends Animal {</p>
<p>  public function __construct($id) {<br />
    $this-&gt;getPenguinFromDb($id);<br />
  }</p>
<p>  public function getPenguinFromDb($id) {<br />
    // elegant and robust database code goes here<br />
  }</p>
<p>  public function __get($field) {<br />
    if($field == 'name') {<br />
      return $this-&gt;username;<br />
    }<br />
  }</p>
<p>  public function __set($field, $value) {<br />
    if($field == 'name') {<br />
      $this-&gt;username = $value;<br />
    }<br />
  }<br />
}<br />

penguin3.php

In this way we can falsify properties of objects, for any one of a number of uses. As I said, not a way to build a whole system, but a very useful trick to know.

__call

There are actually two methods which are similar enough that they don’t get their own title in this post! The first is the __call method, which gets called, if defined, when an undefined method is called on this object.

The second is __callStatic which behaves in exactly the same way but responds to undefined static method calls instead (only in new versions though, this was added in PHP 5.3).

Probably the most common thing I use __call for is polite error handling, and this is especially useful in library code where other people might need to be integrating with your methods.

So for example if a script had a Penguin object called $penguin and it contained $penguin->speak() ... the speak() method isn’t defined so under normal circumstances we’d see:

PHP Fatal error: Call to undefined method Penguin::speak() in …

What we can do is add something to cope more nicely with this kind of failure than the PHP fatal error you see here, by declaring a method __call. For example:

<br />
class Animal {<br />
}<br />
class Penguin extends Animal {</p>
<p>  public function __construct($id) {<br />
    $this-&gt;getPenguinFromDb($id);<br />
  }</p>
<p>  public function getPenguinFromDb($id) {<br />
    // elegant and robust database code goes here<br />
  }</p>
<p>  public function __get($field) {<br />
    if($field == 'name') {<br />
      return $this-&gt;username;<br />
    }<br />
  }</p>
<p>  public function __set($field, $value) {<br />
    if($field == 'name') {<br />
      $this-&gt;username = $value;<br />
    }<br />
  }</p>
<p>  public function __call($method, $args) {<br />
      echo &quot;unknown method &quot; . $method;<br />
      return false;<br />
  }<br />
}<br />

penguin4.php

This will catch the error and echo it. In a practical application it might be more appropriate to log a message, redirect a user, or throw an exception, depending on what you are working on – but the concept is the same.

Any misdirected method calls can be handled here however you need to, you can detect the name of the method and respond differently accordingly – for example you could handle method renaming in a similar way to how we handled the property renaming above.

__sleep

The __sleep() method is called when the object is serialised, and allows you to control what gets serialised. There are all sorts of applications for this, a good example is if an object contains some kind of pointer, for example a file handle or a reference to another object.

When the object is serialised and then unserialised then these types of references are useless since the target may no longer be present or valid. Therefore it is better to unset these before you store them.

__wakeup

This is the opposite of the __sleep() method and allows you to alter the behaviour of the unserialisation of the object. Used in tandem with __sleep(), this can be used to reinstate handles and object references which were removed when the object was serialised.

A good example application could be a database handle which gets unset when the item is serialised, and then reinstated by referring to the current configuration settings when the item is unserialised.

__clone

We looked at an example of using the clone keyword in the second part of my introduction to OOP in PHP, to make a copy of an object rather than have two variables pointing to the same actual data. By overriding this method in a class, we can affect what happens when the clone keyword is used on this object.

While this isn’t something we come across every day, a nice use case is to create a true singleton by adding a private access modifier to the method.

__toString

Definitely saving the best until last, the __toString method is a very handy addition to our toolkit. This method can be declared to override the behaviour of an object which is output as a string, for example when it is echoed.

For example if you wanted to just be able to echo an object in a template, you can use this method to control what that output would look like. Let’s look at our Penguin again:

<br />
class Penguin {</p>
<p>  public function __construct($name) {<br />
      $this-&gt;species = 'Penguin';<br />
      $this-&gt;name = $name;<br />
  }</p>
<p>  public function __toString() {<br />
      return $this-&gt;name . &quot; (&quot; . $this-&gt;species . &quot;)\n&quot;;<br />
  }<br />
}<br />

penguin5.php

With this in place, we can literally output the object by calling echo on it, like this:

<br />
$tux = new Penguin('tux');<br />
echo $tux;<br />

I don’t use this shortcut often but it’s useful to know that it is there.

More Magic Methods

There is a great reference on the php.net site itself, listing all the available magic methods (yes, there are more than these, I just picked the ones I actually use) so if you want to know what else is available then take the time to check this out.

Hopefully this has been a useful introduction to the main ones, leave a comment to let us know how you use these in your own projects!

'Coz sharing is caring