News Feed
Jobs Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Tutorial:
An Introduction to OOP in PHP
June 28, 2006 @ 12:14:05

Okay, show of hands out there - who else is tired of the boring old car analogies when it comes to talking about object-oriented programming in PHP? I have to admit; even I got a little sick of reading them after a bit. It seemed like there wasn't much originality behind them, and several of them just assumed that you understood what "$this->car_name" was.

So, here we go with something a little bit different - hopefully it'll turn out to be something useful for all of you developers out there trying to wade through the wide world of object-oriented programming with PHP.

Read on for the rest of the tutorial!

What's so cool about OOP anyway?
Well, let's start at the beginning and lay down some basic terms to get things started. First off, most PHP developers write when their first coming into the language is called "procedural". In this kind of code, one thing happens after another and the most exciting thing that could happen is the inclusion of another file. Functions are scattered here and there, and a library of them may even be used to help move things along a bit faster. There are limitations to this kind of programming, though. Procedural code tends to get pretty unwieldy pretty quickly when working with larger site. Shifting things around to included files helps, but it doesn't get to the root of the problem.

Object-oriented programming can help with all of this. Let's back up just a second and talk about what the "object" part in that term means. Objects are variable types in PHP that can do all sorts of fun things. They can be passed around from place to place all while maintaining all of their properties and methods inside. If that doesn't make sense to you yet, hang with me a bit, I'm going to help. The first step is to discover how to create an object of your very own.

The Object of Our Affections
Objects are really just a fancy variable type (as mentioned above) with some nifty features that come along with them. To create an object, you'll need something called a class. Think of a class as the framework behind an object that defined the functionality and variables to keep inside. Here's an example:


<?php
class myClass {
    function 
myClass(){    
    }
}
?>

In this case, "myClass" is, well, the name of the class and the word "class" is a keyword that PHP looks at to know what you're doing. Right inside the class definition, there's a function, "myClass". Now, I'm not trying to confuse you on purpose - there's a reason why it's named the same as the class. It's a special kind of function called the constructor. Just like laying the foundation and putting up the walls of a new building is part of constructing it, our "myClass" function is run when the object is first created.

Ah! Now to the fun part! Object creation! (Well, not so much fun as the next step in the process).

So, we have our little sample class above sitting there, ready to use. But, to be able to get to anything inside it, we need to make an object that represents it. Here's an example:


<?php
$mine
=new myClass();
?>

Man that's hard work...well, okay - so it's not, but there's still a little there to explain. The variable "$mine" is the newborn object. If you do a print_r() on it (you do know about print_r, don't you?), you can see that it's a little bit special. To tell PHP that we want to make it an object, we use the "new" keyword along with the name of the class. Our example above doesn't really do anything yet, but that's about to change when we introduce properties.

Putting Properties Into the Mix
Like everything else involved with classes, properties are really just something you already know (and love). Properties are just variables in disguise. Why are they different? Well, Inside of a class, you can have variables, but there are some variables that ascribe to a higher calling. These variables can be accessed both inside and outside of the class and are global inside an object. Want an example? Here's a simple one:


<?php
class myClass {

    var 
$my_var 'testing';

    function 
myClass(){
    }
}
$mine=new myClass();
echo 
$mine->my_var;
?>

In our example above, we're using the same class structure as before, but we've added something different. The "$my_var" variable defined at the top puts that value out where we can get to it later. Later comes around when, after creating the object, we have some fun with a new operator entering the game, the "->" (or as I usually call it, the arrow). Basically, this tells PHP that the variable you're referencing is a part of the "$mine" object. PHP automatically pulls the current value from the object and echoes it out just like any other value. And this isn't limited to just variables, either - you can use the arrow to call methods too (functions in a class, remember), like so:


<?php
class myClass {
    function 
myClass(){
    }
    function 
echoMe(){
        echo 
'me';
    }
}
$mine=new myClass();
$mine->echoMe();
?>

Running this script will result in the text "me" being output to the page. Pretty simple, huh?

Taking the Next Step
Since we're starting to get a bit more complex anyway, why don't we apply all of this great knowledge that we've already accumulated into something a bit more useful - like a simple graphical example. In this example we're going to create a box on the page (a DIV tag) and with the help of PHP and some CSS, change a few things about it. But first, the code:


<?php
class myHappyBox {

    var 
$box_height 100;
    var 
$box_width 100;
    var 
$box_color '#EC0000';

    function 
myHappyBox(){
    }

    function 
setHeight($value){
        
$this->box_height=$value;
    }
    function 
setWidth($value){
        
$this->box_width=$value;
    }
    function 
setColor($value){
        
$this->box_color=$value;
    }

    function 
displayBox(){
        echo 
sprintf('
            <div style="height:%spx;width:%spx;background-color:%s"> </div>
        '
,$this->box_height,$this->box_width,$this->box_color);
    }
}
$box=new myHappyBox();
$box->displayBox();
?>

Now, don't let this code scare you off, it's really not that complex. There's a few new things to look at in here, but nothing that doesn't make sense with the right explanation. We know that we're going to be building a box with this class, so we know that the box is going to have certain properties - height, width, and a color. Looking at the class above, you can see those three settings defined as properties with default values. By defining them there at the top, we have settings to fall back on if we do like the example shows and just call displayBox(). As it stands, the example will show a 100 pixel by 100 pixel DIV with a red background. This is all well and good, but what happens if we want to change one of these settings? Well, that's what the other functions are for.

There are three "set" functions in our myHappyBox class - one for height, one for width, and one for the background color - and they all work the same basic way. Each of them takes in a value and sets the global (to the object) property to the new value. So, if we wanted to change the size of the box, we could do:


<?php
$box
=new myHappyBox();
$box->setHeight(30);
$box->setWidth(300);
$box->displayBox();
?>

The above code would then alter our default box and display one that's a whole lot wider than it is tall. The same kind of change can be made with the setColor method, giving it a value of an HTML color (hex).

Wrapping it all up
So, that's basically it - not really anything to be scared of or to avoid for the future. In fact, object-oriented programming can be one of the better things to happen to you and your code. Sure, rewriting that application you're currently on in a more "OOP fashion" might be a big pain, but there's always the next project to consider. And remember, there's more to working with objects, classes, methods, properties, blah, blah, blah than what I've said here. You should definitely head over to the PHP.net site and check out their great resource on the topic. It has the answers to the questions you'll want to know now that you're finished with this little tutorial.

83 comments voice your opinion now!
phpdev tutorial introduction object-oriented programming beginner phpdev tutorial introduction object-oriented programming beginner


blog comments powered by Disqus

Similar Posts

99Points.info: Youtube Style Share Button With URL Shortening using CURL, jQuery and PHP

CodeUtopia.net: Is PHP a good first language?

Zend Developer Zone: Whip Up a Yahoo! Mashup Using PHP

Gergely Hodicska's Blog: What's new in PHP 5.3 - part 1: namespaces

Community News: PHPEasy.co.uk Launched


Community Events











Don't see your event here?
Let us know!


hhvm package symfony2 example install framework facebook podcast introduction security opinion unittest application overview code component release language hack composer

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework