PHP is so much more than a scripting language. It's a full-fledged language capable of building very complex applications. By harnessing the full power of Object Oriented Programming, you can reduce the amount of time you spend coding and use it to build better websites. This tutorial will show you how.
What is OOP?
OOP stands for Object Oriented Programming. OOP is a programming paradigm wherein you create "objects" to work with. These objects can then be tailored to your specific needs, to serve different types of applications while maintaining the same code base. Quite useful indeed.
What is an object?
An object is simply a copy or instance of a "class". A class can be defined as a "black box" from where we create our objects and access its attributes (variables) and methods (functions). The most common analogy given when explaining classes and OOP is how you drive a car: basically, you have 2 or 3 pedals, a gear stick and a steering wheel. You don't need (and most probably don't want) to know how the car works when you press the pedals. You just want your car to go back and forth, left and right. And OOP is precisely that. You don't need to know how the methods of a class work (if you didn't implement it yourself), just what they do. OOP is also useful if you have a large number of objects of the same type in a system: you just have to create the objects and then manipulate them all in the same way, without rewriting any code. Moreover, an object is able to maintain it's state (variable values and such) throughout the execution of the program.
The implementation of "Car" is hidden from us, however we can use its full capacities.
OOP in PHP
PHP 5 (although most of the ideas in this article also apply to PHP 4) has great support for object oriented programming by providing easy class creation. PHP provides every paradigm other "true" OOP languages implement (Python and JAVA, for example), like inheritance, polymorphism and encapsulation.
Inheritance
The basic idea behind inheritance is that similar objects share common properties. So by creating a "generic" class, we can have a blueprint to build our subsequent classes on. Imagine, if you will, a car's properties: color, number of wheels, horsepower, number of seats, etc. Having this template we can further specialize our cars by extending this class: creating a racing car that has a "nitro" property, or a truck that has a "trailer" property. The bottom line is: create a more generic class that contains most of the common attributes and you will have much less work defining other objects only slightly different. Instead of rewriting the whole code, you just extend it's properties, saving a lot of time in the process.
Inheritance diagram for our car classes.
Encapsulation
As previously explained, one of the main advantages of using objects is that we don't need to reveal all of its members (attributes or functions); just the necessary interfaces to work with it. Details not useful to the use of these objects should be hidden from the rest of the objects. This is what is referred to as encapsulation.
Levels of visibility
- public: means that a class member is visible and usable / modifiable by everyone
- private: means that a class member is only usable / modifiable by the class itself
- protected: means that a class member is only usable / modifiable by the class itself and eventual sub-classes
NOTE: By default, in PHP, a class member is public unless declared private or protected. Check out an example here.
Polymorphism
Polymorphism is an OOP characteristic that allows the programmer to assign a different meaning or usage to something in different contexts - specifically, to allow a class member to perform different tasks depending on the context it was used. Imagine you have a Person class and two sub-classes of Person: Japanese and American. Both implement a function named talk(), but with different languages and social context. And while both of them are basically People (as they derive from the class Person), their implementation of the function talk() is very different. So you basically have two objects of the class Person in which the talk() function works differently.
Getting our hands dirty
Ok, now for the real action. We will be creating a simple class to handle image manipulation and information extraction. For the duration of this tutorial I will assume you have a basic understanding of PHP (variables, creating functions, working with control flow statements and loops). Reading the GD PHP manual will remove any doubts you may have about image handling functions.
Step 1: Creating our class
We start by defining our class:
<?php
class Image {
}
?>
This just tells PHP we will start defining a new class, named "Image". Now we will define the class constructor. A constructor is simply the function that is called when creating a new object. In PHP 5 this can be achieved by two different methods: creating a public function with the exact same name of the class (PHP 4 and on) or by creating a function called "__construct()" (PHP 5 only):
Step 2: Creating the class constructor
The following two pieces of code do exactly the same thing:
<?php
class Image {
public function Image() {
echo "We just created and object!";
}
}
$image = new Image(); // prints "We just created and object!"
?>
<?php
class Image {
function __construct() {
echo "We just created and object!";
}
}
$image = new Image(); // prints "We just created and object!"
?>
NOTE: A class constructor is always public.
Class constructors should be used to ensure that the created object has a minimal amount of data to work with; in our case, the desired image.
As such, the first thing we have to do is to read the image, whatever it's type may be. Currently, the GD library supports a number of image types, such as jpg, png, gif, bmp, and others; we just have to read the image and determine it's type.
<?php
class Image {
function __construct($filename) {
// read the image file to a binary buffer
$fp = fopen($filename, 'rb') or die("Image '$filename' not found!");
$buf = '';
while(!feof($fp))
$buf .= fgets($fp, 4096);
// create image
imagecreatefromstring($buf);
}
}
$image = new Image("image.png"); // If everything went well we have now read the image
?>
So what have we done? To open the image as effortlessly as possible, we will be using GD's function imagecreatefromstring (which takes a binary string of data as input), instead of imagecreatefromjpeg, imagecreatefrompng or imagecreatefromgif, for example.
So we try to open an image file and assign it's file pointer to $fp, and, in case of failure, terminate the program's execution.
$fp = fopen($filename, 'rb') or die("Image '$filename' not found!");
Next, we create an empty string to hold our data...
$buf = '';
...and read the whole file, concatenating the data read with our newly created string contents.
while(!feof($fp)) $buf .= fgets($fp, 4096);
Now we just have to create our image using the data we just read...
imagecreatefromstring($buf);
... and create an object to use all these functions.
$image = new Image("image.png");
NOTE: jpg, png, gif and most image files need to be read in binary mode, hence the "rb" passed as the second argument of the fopen function. "r" means read-only and "b" means binary.
Step 3: Defining class attributes and methods
In it's current form our class isn't very useful. So we will be adding some attributes and methods to make it more useful. So we will start by 1: defining some internal variables (note the "private" visibility declaration before each variable)
<?php
class Image {
// class atributes (variables)
private $image;
private $width;
private $height;
private $mimetype;
function __construct($filename) {
// read the image file to a binary buffer
$fp = fopen($filename, 'rb') or die("Image '$filename' not found!");
$buf = '';
while(!feof($fp))
$buf .= fgets($fp, 4096);
// create image and assign it to our variable
$this->image = imagecreatefromstring($buf);
// extract image information
$info = getimagesize($filename);
$this->width = $info[0];
$this->height = $info[1];
$this->mimetype = $info['mime'];
}
}
$image = new Image("image.png"); // If everything went well we have now read the image
?>
And 2: a method to display the image.
<?php
class Image {
.
.
.
public function display() {
header("Content-type: {$this->mimetype}");
switch($this->mimetype) {
case 'image/jpeg': imagejpeg($this->image); break;
case 'image/png': imagepng($this->image); break;
case 'image/gif': imagegif($this->image); break;
}
//exit;
}
}
$image = new Image($_GET['image']); // If everything went well we have now read the image
?>
In this step we just created some class attributes (image, width, height and mimetype) to hold the object's data. Then we made some modifications to assign the created image to our class attribute $image...
$this->image = imagecreatefromstring($buf)
... and extracted the image's informations to our remaining class variables (read the documentation on getimagesize to fully understand how the image information is read):
// extract image information $info = getimagesize($filename); $this->width = $info[0]; $this->height = $info[1]; $this->mimetype = $info['mime'];
Next we created a function that outputs the image to the browser by defining the appropriate headers (read more on http headers here) and using the appropriate function (with the switch statement) to output the image based on the original image mimetype (for this tutorial we will just support jpg, png and gif but, as I said before, GD support a multitude of other formats. Read the php documentation for more).
So what's this "$this" stuff in there? "$this", in PHP, refers to the class itself, and it's used to point to class attributes or functions. As such, $this->image points to the class attribute named "$image" and $this->image = ... changes the value of the class attribute. If you were to write $image = ... you would just be creating a new local variable named "$image", available exclusively for the duration of the function. This is one of the main things to pay attention to when creating classes in PHP.
Our not very useful (yet!) display method.
Step 4: Defining our "Thumbnail" sub-class
Right now our class isn't very useful. Sure, we can read our image and display it, but that's it. We will now create a sub-class to create our thumbnails. (We really don't need to create a sub-class, but we will for the sake of the tutorial, to demonstrate inheritance and polymorphism). So, for the inheritance to work properly we need to slightly change the definition of our super-class (Image). We just need to change the visibility of our class variables from "private" to "protected". And now we will create the constructor of our subclass.
<?php
class Image {
// class atributes (variables)
protected $image;
protected $width;
protected $height;
protected $mimetype;
.
.
.
}
class Thumbnail extends Image {
function __construct($image, $width, $height) {
// call the super-class contructor
parent::__construct($image);
// modify the image to create a thumbnail
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
$this->image = $thumb;
}
}
?>
So what exactly are we doing here? We created a new class, derived from our original, meaning that we can access all of its public and protected attributes and methods. We call the super-class constructor, responsible for reading the image and extracting its information. The sub-class constructor does not call its superclass constructor so we need to call it explicitly.
Now we create a new image for our thumbnail, with the width and height passed:
$thumb = imagecreatetruecolor($width, $height);
Resample (resize) the original image into the new one, to create the thumbnail:
imagecopyresampled($thumb, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
And finally modifiy the original image to contain the thumbnail instead of the full-size image:
$this->image = $thumb;
And guess what? We don't really need to write a new function to display the thumbnail because the same principle applies, whether you are displaying a full size image or a thumbnail. After all, it's still an image! So we just need to call our display() function, defined in the super-class, and we're done!
Our completed class and respective sub-class.
And that concludes our tutorial. As an exercise I, suggest you implement a function to save the generated thumbnails to disk instead of outputing it on the fly (Where should you implement that function? In the super or sub-class?). Good luck and check the zip provided for an example usage and the full classes developed here (you need to have a PHP powered server to test it).
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.












User Comments
( ADD YOURS )dorian January 19th
im first
( )Shuuun January 19th
first =D
and “oh noeeees” ^^
( )I wanted to record an oop php video tutorial for beginners
that was one of the things you did not tutorialized on this page
and now its done :O
Semiotikus January 19th
“NOTE: A class constructor is always public.”
Actually, the constructor does not have to be public.
( )It is common to have the constructor protected/private i.e. in Singleton Pattern.
DKumar M. January 19th
Nice tutorial for beginners in PHP Object Oriented Programming. Thanks for sharing !!
( )Justin January 19th
Nice Beginner Tut.
One Note, you can have private and protected constructors in PHP5
( )p4bl0 January 19th
Nice tutorial, i read it quickly but i noticed a little error :
“$this”, in PHP, refers to the class itself
In fact, “$this” refer to the OBJECT, the instance of the class. In order refer to the class itself, the keyword “self” should be used, (like “parent” for instance).
( )insic January 19th
very informative for the PHP beginners. thanks for the post
( )Benni January 19th
Thats wrong. You can set it private and have to use it private if you want wo use just one instance of a class (Singleton Pattern). That´s important for database connections.
( )pixelsoul January 19th
very nice.
( )AJ January 19th
very nice tut
( )Ed Baxter January 19th
Great Tutorial
( )GrassyHill January 19th
Nice refresher. Been so long since I OOPed everyday that I almost forgot why it was the cat’s pajamas
( )Router January 19th
lol, I’ve just discovered this Image Class: http://og5.net/christoph/article/Image_Wrapper_and_Uploader a second before I read this tutorial – seems like a little more advanced!
( )Max January 19th
thx for the tutorial.
( )Vasili January 19th
I really like this tutorial. It is easily understandable, and does the job perfectly!
( )wassim January 19th
@Benni – In the world of OOP and as a general rule, PROTECTED methods aren’t often used because of the OPEN for interactivity nature of most web applications, but protected methods are indeed useful in limiting the access to some special forms, in this case the subclasses should call a protected constructor, otherwise a public constructor is just enough.
Nice shot João
( )Craig January 19th
Another great way to save time and stay in OOP is to look in the prebuilt php frameworks to make your next website! PHP Cake is my personal favorite.
Private class are the correct way to do Singletons, however there are other alternatives to create singletons. I know I run into that problem with actionscript since private classes are not allowed.
( )Markus January 19th
cheers mate
( )Timothy January 19th
Nice post. And, for anyone not familiar with OOP, you should try it out. OOP is a very, very popular paradigm.
I tend to use classes for database connectivity and queries. You wouldn’t think it would be all that useful until you try it. Then, you won’t want to stop.
I hope this post influences some newbie programmers to go the OOP way.
( )Martinho January 19th
Obrigado Joao Gardim,
Vou colocar nos meus favoritos. Ainda não sei programar em PHP. Mas em breve vou aprender.
Nice Tut
( )Martin January 19th
Pretty good article this time around.
( )Shuuun January 19th
nope, link works fine, try again
( )Dixon January 19th
Ugh! I just finished my tutorial on OOP for Nettuts!
Gah.
( )M.A.Yoosuf January 19th
ha ha, now corrected, and my comment removed.
by the way nice flow of article, keep it up
( )jordan stephens January 19th
I was just reading about this last night…
( )Xeoncross January 19th
Glad to see people finally pushing OOP even on design-centered websites. Dealing with code in packages (classes) is so much easier than just having a free-running mess of PHP.
( )Jeffrey Way January 19th
@Dixon – That’s okay! Send it in still.
( )crysfel January 19th
@João Gradim
but it is ok, you are doing it good.
you are student!! need to read/learn more
have funnnnnnn
( )halli January 19th
great!
http://www.quickurl.biz
( )wassim January 19th
@Dixon – It’s Ok. João’s tutorial is tagged “ASAP”, tag yours as “TYT” (take your time) and the trick is done. LOL
( )grrrrr8 January 19th
Anyone knows of a good book on this subject
( )Kevin Quillen January 19th
I’d suggest using a framework along with PHP, it will facilitate in development while keeping you somewhat secure. Look up Zend, Cake, CodeIgniter.
( )Fatih January 19th
Thanks, was very helpful.
( )Brenelz January 19th
Great tutorial on PHP OO. I have my own image class that is a little different, but this is a great walkthrough.
I know the theories behind objects, I just find it tough to code everything so generic in a real world project.
( )Doug January 19th
@ grrrrr8
PHP Objects, Patterns and Practise, published by Apress. Perhaps a little heavy going if you are new to OOPHP but I reckon it covers enough base ground to be useful to a beginner.
@ author
( )Nice article, I enjoyed reading it as I do most of the tutorials on this site. As has been noted there are a couple of minor areas of contention but nothing that would prevent your example functioning enough to wet the readers appetite.
Peter January 19th
A basic introduction to objects in PHP but with a number of inaccuracies. Since this is aimed at those only just starting to learn the concepts and to put them to use, perhaps a little more thorough technical proof reading could be done for future articles: just to get things right. Apologies in advance for the negative edge to an otherwise well written tutorial.
( )Miles Johnson January 19th
Constructor IS NOT always public. I put mine on private for singleton classes.
( )Anthony Hastings January 19th
Thanks for this really informative tutorial. It’s well written; in a way that anyone of any experience level in regards to PHP and OOP can understand. I’ve been looking at it for a while now and would like to start using it more and more in database calls and queries. I’m still not sure how to start that off from doing this tutorial, but nevertheless it was a great beginners read.
Thanks and keep up the great work,
Anthony
( )Hasanga January 19th
Alright! this is grate!
Why not you guys out there write some more advance OOP tuts with PHP.
Keep em coming guys! keep em coming!
( )Johnb January 19th
After years of on and off learning of OOP, i come across this article. Thanks a lot! My brain has such a hard time wrapping itself around the more advanced OOP features. This article helps. I think i’ll read it again!
( )klaus January 20th
Cool quite helpful. Thanks for Sharing
( )Andy January 20th
I agree with Hasanga. We need more OOP tuts
Great job!
( )Daniel January 20th
Very nice tutorial for PHP Object Oriented Programming.
( )Mr. Magic January 20th
Overall a good one. Even the inheritance example actually makes some sense.
I would like to point out that the constructor example and visibility keywords are a bit vague:
PHP5-style: Always use __construct as constructor name, ALWAYS declare visibility: public, protected, private – for ALL methods and properties, including constructor!
PHP4-style: Constructor name is class name. No visibility keywords.
DO NOT mix PHP4 and 5 styles! End result is plain confusion to which is the correct syntax.
I would recommend using error_reporting(E_ALL|E_STRICT); so that you can see if your code is using PHP4 syntax (will display errors if you use deprecated syntax)
( )HK January 20th
PHP isn’t a “true” object-oriented language… at least not compared to Ruby:
“I’m a full-fledged object”.reverse!
( )Roy Vergara January 20th
great startup lesson for OOP! another great resource that helped me out was http://www.killerphp.com/tutorials/object-oriented-php. keep up the good work!
( )Brian Reindel January 20th
Just to be clear, the code execution in __construct() happens before the object reference is returned. That means you are initializing code before the object is created, and not at the time the object is created. For most developers this will never matter, but it is handy to know.
@Jeffrey I had started a PHP OOP tutorial as well for Nettuts… oh well, I guess I’ll send it in and hope for the best.
( )Join January 20th
Nice tutorial
Thanks you
For good way of OOP I thinks you need setup properties for that object
( )Eneza January 20th
Very Good Argument! A bad post become Great with the Arguments sent!
( )Maurizio Liberato January 21st
Very nice and useful tut! Even though I think, for personal experience, that Asp.net with C# works much much better for OOP. It’s worth learning it!
( )Renato Carvalho January 21st
Olá, João. Sou do Brasil e gostaria de saber se você tem esse tutorial em português. Um abraço!
( )Brian Reich January 21st
Fantastic beginner’s tutorial! It’d be nice to see a follow-up describing some of the more powerful (if a bit confusing) aspects of OOP in PHP, such as magic methods, object serialization, and extending classes and implementing interfaces in the Standard PHP Library (SPL).
( )Tuno January 22nd
Bom tutorial para iniciados, parabéns!
Raro vermos materiais de portugueses, pena não fazeres uma versão em pt.
Cumprimentos
( )Bob Brown January 22nd
Nice tutorial … the difference between function image() and function __construct() is that the eponymous function (named after the class) is for backward compatibility with PHP4. If writing for PHP5+ (which most people will be now) simply use __construct().
I’ve done a similar blog post on classes in PHP but didn’t go into subclasses. My post covers methods and properties, and uses vehicles as the sample object.
Check it out at http://www.guru.net.nz/blog/tutorials/intro-to-classes
( )Leonardo Mangione January 22nd
Muito bom João.
GOstei da ideia de você aplicar de cara o que estavamos aprendendo em um exemplo pratico.
Parabens.
( )Dan Gayle January 22nd
@grrrrr8
( )PHP Object Oriented Solutions, by David Powers, is a great book on the subject.
Saeed Jabbar January 22nd
This is great and well explained. For those of you who want to get more in depth with OPP check out PHP5 Advanced by Larry Ullman.
( )João Gradim January 22nd
Thank you all for your kind replies.
Para quem perguntou se tenho o tutorial em português: infelizmente não e não tenho disponibilidade para o fazer.
( )Patrick January 24th
Good Tutorial!
Thx a lot!
( )Tom January 24th
Nice Tutorial, im just breaking into OOP, but am still lazy, and dont use it!
( )Some Funky Dud January 24th
Good beginners tutorial, OOP is a bit confusing at first, and this tutorial doesn’t cover every aspect of it, but for starting out, it’s very well written, easy to follow, lots of examples (good for visual learners like myself) and step by step code breakdowns.
Thanks.
( )Philips Tel January 25th
Nice tutorial as always nettuts…
Would you write a tutorial how to build a simple website by OOP way??
Because I’m a beginner and few expriences in OO PHP.
thx!
( )Steve January 26th
love to see a OO jquery tut
( )Mike January 30th
Very understandable thanks so much! great tutorial
( )Sykespro February 2nd
Nice One! Keep it up!
( )Velha Guarda February 3rd
boavista panteras negras. parabens!
( )santosh February 4th
nice and simple article…..good
( )gulsha February 5th
very nice
( )javi February 7th
João Gradim
nice tut.
this is why I like PHP. it’s easy and it’s fast.
( )jacker'sphan February 9th
thanks you
( )Unknown February 12th
Nice tut dude…thanks a lot
( )Ruben February 12th
Note that you should unset any variables that you know take up system resource, in this case images also. You can do that with the method __destruct(), wich is the opposite of __construct(), it can not accept any variables, however it is run when your instance of your class is unset (either automatically or with unset() )
( )Julian February 24th
n1 for refreshing knowledge!
( )Tareq April 25th
Nice Tutorial. Thanks
( )kilinkis May 25th
awesome tutorial! thank you very much, it was very useful
( )Stuart June 7th
Very clear, Nice work!!
( )amit sinha June 25th
nice tutorials
( )Shaney June 28th
brilliant, keep it up
( )Syk July 2nd
Nice and simple article.
( )Thanks for your suggestion.
Keep going
Immanuel July 18th
Awesome tutorial!
Is there a variation of this perhaps that could create the thumbnail just by specifying the height variable?
( )MOUZA July 21st
thanks…
( )Mahmoud Al Ramamneh August 25th
gr8 article thank you dude
( )redfew October 22nd
ok
( )redfew October 22nd
Cuteeeeeeee tute. Keep up ur good work
( )yorg October 26th
Boa João.
( )è bom ver cena “tuga” por aqui.
Srivathsa November 3rd
Its really a helpful tutorial for beginners, that boosted me to learn more OOPS in PHP
( )Jahmaica November 7th
Yeh João, rápido e eficaz,
( )dois abraços, um de Cascais e outro de Moçambique
fouzan November 19th
its good but not all info for beg we need more
( )