An Introduction to OOP in PHP
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] [/php]
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:
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] <?php class myClass { <pre>var $my_var = 'testing'; function myClass(){ }
} $mine=new myClass(); echo $mine->my_var; ?> [/php]
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] <?php class myClass { function myClass(){ } function echoMe(){ echo 'me'; } } $mine=new myClass(); $mine->echoMe(); ?> [/php]
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] <?php class myHappyBox { <pre>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(); ?> [/php]
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] <?php $box=new myHappyBox(); $box->setHeight(30); $box->setWidth(300); $box->displayBox(); ?> [/php]
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.
tagged:	phpdev	tutorial	introduction	object-oriented	programming	beginner	phpdev	tutorial	introduction	object-oriented	programming	beginner
New Object Oriented PHP Book
Over on php|architect's site, there's a mention from Marcus about a new book from No Starch Press called "Object-Oriented PHP: Concepts, Techniques, and Code" (by Peter Levin) along with a little review.
"Object-Oriented PHP" is ideal for the developer who wants to learn object-oriented programming in PHP. If you already know how to use objects under PHP 4 this will get you up to speed with PHP 5. If you don't know anything at all about object-oriented programming, what better way to start than with the straightforward approach of PHP?
He has good things to say about the book, noting that it's laid out well, provided ample descriptions about the code and concepts presented, and helps you get the most out of your PHP5 programming.
You can purchase the book directly from the No Starch Press website in either paperback ($39.95 USD), a PDF version ($19.95 USD), or a combination of both ($43.95 USD). There's even a sample chapter if you want to try before you buy.
tagged:	object-oriented	book	review	concepts	techniques	php5	object-oriented	book	review	concepts	techniques	php5
PHPBuilder.com:
Object-Oriented Features New To PHP5
For those who have yet to make the leap over from PHP4 to PHP5, it'd be worth your time to check out this new article from PHPBuilder.com detailing some of the object-oriented features that are new to this more advanced version.
With the release of PHP 5 in 2004 there was plenty of room for improv- ing PHP's OO capabilities. At this point, Java, the most popular OO language to date, had already been around for almost 10 years. Why did it take PHP so long to become a full-fledged OO language? The short answer is because PHP is principally a web development language and the pressures of web development have only recently pushed it in this direction.
Their "long answer" goes through each of the changes that have been made (like access modifiers, built-in classes, web services, and reflection classes) explaining them in the context of comparing them back to PHP4. They also include a "where to go from here" section to advise on how to take that first step to PHP5-ness.
tagged:	object-oriented	features	php5	php4	compare	adoption	object-oriented	features	php5	php4	compare	adoption
Using Recursive Methods in Object-based PHP Applications (Part 2)
DevShed has posted part two of their series dealing with recusion in PHP, this time with a focus on its use in a more object-oriented environment.
Welcome to the second tutorial of the series "Recursion in PHP." Comprised of three parts, this series introduces the fundamentals of recursion in PHP, including the definition and use of recursive functions in procedural PHP scripts, as well as the creation of recursive methods in object-oriented Web applications.
Now, in this second part of the series, I'll explore some advanced uses of recursion in PHP, particularly in the terrain of object-oriented programming. I will develop a couple of object-based applications which use recursive methods for accomplishing their tasks. By the end of this tutorial, you should have a pretty solid grounding in how to define recursive methods within your own PHP classes.
They start with a simple example of OOP with recursion, handling some "HTML widgets" to be output to a page (div, h1, p, and ul tags). With this library created and in place, they work up a "generator" class to actually build the page dynamically. Finally, they bring it all together with the creation of a simple template processor for simple page creation.
tagged:	recursion	object-oriented	tutorial	part2	template	html	recursion	object-oriented	tutorial	part2	template	html
An Object-based Approach to HTTP Compression in PHP
DevShed has posted part two of their series on speeding up your page load times with HTTP compression, this time looking at a more object-oriented approach to handling the data you want to compress.
Over the first tutorial of this series, I developed some hands-on examples, aimed at illustrating how "Gzip" encoding can be used within PHP scripts to compress the output generated by dynamic PHP pages. After transferring the encoded data to the client, contents are uncompressed and finally displayed on the browser.
By the end of this article, you should have the appropriate knowledge for building a simple data compressor class, in addition to using HTTP compression for reducing the download time of object-generated web pages.
They start with the creation of a simple data compression class, with functions to see if the browser supports gzip encoding and to get/send/compress the actual data. With the sample class created, they put it to the test with a more real-world example - echoing out user information from a MySQL database.
tagged:	gzip	compression	buffer	output	object-oriented	gzip	compression	buffer	output	object-oriented