Curated by Carsonified

Learn with Treehouse

Accessibility, CSS3, Design, Django, HTML & CSS, HTML5, JavaScript, jQuery, NoSQL, PHP, Responsive Web Design, Ruby, Ruby on Rails, Tools, UX, Version Control, WordPress, iOS and more

Article 17

Getting Started with OOP & PHP5: Part 2

By

01 April 2010 | Category: Code, PHP

This post follows on from my first article "Getting Started with OOP & PHP5" which introduced the basics of Object Orientated Programming and what that looks like in PHP.

This time around we'll look at some more advanced concepts and some more practical examples of building code, covering use of constructors and how to add access modifiers in to control how calling code can operate on your objects.

We'll also show off how to create static methods and properties and, perhaps more importantly, illustrate applications of these features.

Constructors

Let’s start at the very beginning, and look at what happens when we create an object. When a class is instantiated and used to create an object, a particular function is run and this is called the constructor. The way this is done changed between PHP version and so can be a bit confusing.

In PHP 4, the constructor was a function with the same name as the class itself – and although PHP 4 is dead and gone (deprecated and no longer supported even for security fixes), that behaviour has been preserved in PHP 5 to preserve backwards compatibility, and you will still see it in code which transitioned between the language versions. Here is an example:

class Penguin {

public function penguin($name) {
$this->name = $name;
$this->type = "penguin";
return true;
}

}

penguin_deprecated.php

So in PHP 5, this would still work, but really we want to use the magic methods introduced in that version, where the constructor is called __construct() and our class would then look like this:

class Penguin {

public function __construct($name) {
$this->name = $name;
$this->type = "penguin";
return true;
}

}

penguin.php

The PHP 5 version makes more sense because the method can then be inherited, rather than having to redeclare a same-named function and call the function which matches the name of the extending class? Confused? Me too :) Always use __construct() is the main message here.

The Static Keyword

So far we’ve looked at fairly classic OO concepts, but to take full advantage of the functionality on offer, there are some more tricks we can learn. One of my favourites (in fact I probably use it too much!) is the static keyword.

The static keyword can be applied to both properties and methods, and we literally mean “static” in this case as to mean “the opposite of dynamic”. When we use static properties and methods, we use the class as it stands, without instantiating it. Sounds a bit strange so let’s take a look at some examples.

Static Properties

A static property is something we can set on an object, either from inside it or from outside, and retrieve it later. It is almost like a constant, something we use for reference, except that it isn’t constant and we can change it at any time.

If you are familiar with using static variables in procedural PHP, then this is a concept that will come easily to you. An example:

class Message {
public static $system_name = 'Default';
}

message.php

This is a very simple class, with a single static property declared. As with all class properties, these can be created and used on the fly since there is no requirement to declare these in PHP.

To access this property, we do not need to instantiate an object of this type. Instead we use the class name followed by the “scope resolution operator” which is two colons, and then the usual dollar sign and variable name we want, like this:

include('message.php');

echo Message::$system_name;

We can modify this variable from outside as shown in the following example, which also illustrates that this property is NOT set on an object instantiated from this class definition:

include('message.php');

Message::$system_name = 'Social Network Messaging';

$msg = new Message();
var_dump($msg->system_name);

echo Message::$system_name;

This script outputs NULL followed by “Social Network Messaging”, as we’d expect.

Static Methods

Static methods follow the same sort of ideas as static properties. They are declared using the static keyword alongside the access modifier (traditionally after it but either order is valid), and they do not require the class to be instantiated.

Static methods are useful for situations where you don’t need any other information to perform the task. For example they are common in the search methods on an object; “findItemByProductId” could be a static method that retrieves some data and then instantiates an object and returns it.

Here’s an example of a simple inflector method; we might want to keep a bunch of these methods together but we don’t need an instantiated object to use them:

class Inflector {
public static function pluralise($word) {
if($word == "sheep") {
$plural = "sheep";
} elseif (substr($word, -1) == 'y') {
$plural = substr($word,0,-1) . 'ies';
} else {
$plural = $word . 's';
}

return $plural;
}
}

inflector.php

When we use this static method we once again use the scope resolution operator:

include('inflector.php');

echo Inflector::pluralise('tree') . "\n";
echo Inflector::pluralise('story') . "\n";
echo Inflector::pluralise('sheep') . "\n";

This script outputs “trees”, “stories” and “sheep” as we’d expect – we don’t need any settings on the objects itself so we never use $this, which is why this makes a good example of using a static class.

Objects, Storage and References

A big change between earlier versions of PHP and PHP 5 is that objects are always passed by reference now, in fact every object is stored simply as a pointer.

This is useful since any changes made to an object passed into a function will persist without us having to pass it back, but it does mean that we can sometimes be tripped up when working with objects and particularly copying them.

Using Clone

So look at this example, what would you expect the output to be?

$a = new stdClass();
$a->name = 'Alice';
$b = $a;
$b->name = 'Beatrice';

echo $a->name;

In fact this example prints “Beatrice”. This is because when we do $b = $a we aren’t copying the values. We’re telling $b that it should point to the same collection of data that $a is pointing to, because objects are just references.

If we want $b to be separate from $a then we will need to make use of the clone keyword, as shown here, only the line where we create $b changes.


$a = new stdClass();
$a->name = 'Alice';
$b = clone($a);
$b->name = 'Beatrice';

echo $a->name;

This time the script outputs “Alice” – our changes to $b don’t affect the values in $a.

As I mentioned before, this change of handling happened between PHP 4 and PHP 5 – and certainly caused some headaches for those that upgraded. However the current behaviour really does work well so it was a good decision in the longer term.

Comparing Objects

Having just said that objects are purely references, we need to bear this in mind when we compare objects – because objects with the same properties set to the same values evaluate differently to two variables pointing to the same object.

For two objects that are of the same types and have all the same property values, we can use the comparison operator “==“. To identify where the same object is being referred to, we can use a strict comparison “===” to evaluate this.

A Question of Class

If you have an object and you want to assess what kind of an object it is, you can do this using the InstanceOf operator. If we go back and use our penguin class from earlier, we can try this out:

include('penguin.php');

$tux = new Penguin("Tux");

if($tux InstanceOf Penguin) {
echo "I'm a penguin\n";
} else {
echo "I don't know what I am\n";
}

Note that since it is an operator, it goes between the object we are assessing and what we want it to be, just like the other operators, such as the less than. Objects will return true to InstanceOf evaluation if they are of that class, implement that class, or extend that class – a very powerful way of identifying if a class will match your needs.

In Conclusion

This article has covered some tools for use of OOP in PHP which I hope will bring you to a point where you feel ready to use this in applications of your own.

A lot of the concepts covered here you might not need every day – but they might catch you out so bookmark this article for reference and refer back any time you need a quick reminder. If you’re using these techniques then do share your tips with other readers in the comments!

Follow @thinkvitamin on Twitter Please check out Treehouse

Other Posts You Might Find Interesting

  • Sorry - No Related Posts Found

Comments

  • ben

    I stopped here:
    “This script outputs NULL followed by “Social Network Messaging”, as we’d expect.”

    What happened there ? What this script did ?

  • http://www.iphp.co.uk Andy Roberts

    Nice article Lorna, look forward to the future parts to build up the whole OOP picture, hopefully some nice examples to explain inheritance, composition, encapsulation, polymorphism and so on.

  • http://doctype.tv Jim Hoskins

    The NULL in the output is created by the code:

    var_dump($msg->system_name);

    The point being illustrated here is when defining static properties, they are not accessible as properties of instances of that class ($msg in this example).

    The more illustrative example is the “correct usage” code:

    echo Message::$system_name

    Which will print out the value of the static $system_name property of Message because it was defined in the code as ‘Social Network Messaging’

    I think the point of the comparison was to show the difference in the syntax between accessing instance properties and static properties. It can be confusing, but PHP does have some interesting design choices that can be jarring when you first learn them.

    Does that help at all?

  • Jaime

    I’m not really a php programmer, since I’ve hated the language since forever (and I have had to use it a lot), but it seems to me that static properties and methods behave like Java’s. They’re basically global variables and functions shoved inside a class namespace right?

  • http://www.twitter.com/mamunabms Abdullah Al Mamun

    I’m really grateful to you for this great series.
    I hope it will be continued………….
    thanks a lot
    :-)

  • http://birkir.forritun.org Birkir Gudjonson

    Forgot to mention method like these are usable in oop like Kohana:

    DB::select(‘id’)->from(‘users’)->where(‘enabled’, ‘=’, 1)->execute();

    In stead of

    $db = new DB;
    $db->select(‘id’);
    $db->from(‘users’);

    $res = $db->execute();

    If I remember correctly, this is php5 only method.

  • http://birkir.forritun.org Birkir Gudjonson

    Forgot to mention method like these are usable in oop like Kohana:

    DB::select(‘id’)->from(‘users’)->where(‘enabled’, ‘=’, 1)->execute();

    In stead of

    $db = new DB;
    $db->select(‘id’);
    $db->from(‘users’);

    $res = $db->execute();

    If I remember correctly, this is php5 only method.

  • http://keycss.com Joao Da Silva

    Thanks Lorna, a very clear way to explain a not so clear technology, well accomplished, passing the message across, thanks.

    more post of this nature.

  • http://www.lornajane.net Lorna Jane Mitchell

    Thanks to everyone who has taken the time to comment :)

    @Jim Hoskins: good explanation, thanks. @ben I hope that helps.

    @Jaime: they’re accessible from anywhere but are not in global scope. You can sort of think of it as a namespace – although we have those in PHP too nowadays. Sorry to hear you haven’t enjoyed using the language but I think the newer versions have more features which would be familiar to computer scientists from other disciplines.

  • Jaime

    @Lorna: So they are like Java’s! In retrospective I can actually think of a use (albeit not something I’d actually use or recommend) for static as such now that I revisited the idea. It’s a decent way to “modularize” a collection of semi-related methods inside one package that won’t cause integration troubles. Regarding the language, I do admit that I’m much happier with Php5, while I completely hated it before. It probably has to do with the fact that I come from a C background, and prefer Ruby as a language for OOP over Php. If it means anything, I’d rather program in Php any day as opposed to Java, though sadly (for me) I work with both in a day to day basis. :)

  • http://blog.valugi.ro valugi

    is this a wrapper for PHP manual or something?

  • http://www.stereoartist.com Ketan Majmudar

    Nice explanation, understood a lot more about the basics, stuff that i’d never understood before (not having learnt OOP concepts before).

    So I decided to code up a little flickr API wrapper for myself and put this newly found knowledge to good use, bound to be mistakes in it !

    http://github.com/stereoket/flickr-curl-php5

    Cheers,

    Ket

  • http://www.lornajane.net Lorna Jane Mitchell

    Now THAT is cool. Nice work Ket – I think you just reminded me why I love to write and teach :)

  • pbgswd

    Lorna, thanks for putting up a good tutorial on these things. I find I have to read about OOP theory over and over to get it, since I dont have opportunity to write classes.

  • http://bene.nu Bene

    thx so much, please continue this tutorial

  • http://natts.com Dave Nattriss

    Good stuff Lorna, thank you.

  • Loïc Teixeira

    Thank you for this great introduction Lorna Jane. It’s been a while since I wanted to jump into OOP. I now have all the keys, no excuse anymore ;-)

    However, some things was still unclear for me. Yes, I say “was”.
    I started writing a comment to ask you whatever was unclear then stopped a few minutes. I ran your script on my localhost, made few test and finally understood.

    One again, thank you, your article was perfect.

Learn Web Design!

Ads Via The Deck

Think Vitamin Radio
Episode #34: Amazon Fire and Responsive Roundtable

Check out our bi-weekly radio show. Covering the hot topics on the web.

Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.

Download Podcast as mp3

Advisory Board

The Think Vitamin Advisory Board in place make sure that you receive the best content possible.