A Beginners Guide To PHP Classes & Objects - Part 1
PHP Classes. A new programmers night-mare. Don’t worry, we where all there at one point.
Before you start to glaze over, let me just state that PHP Classes aren’t complex if you learn them properly. A lot of the time, new programmers will try to learn inheritance, scope etc. right of the bat. I’d be having bad dreams too!
My approach is to teach you in tid-bits. Enough to satisfy those cravings, but won’t cause indigestion.
For the duration of this article, I’ll assume you at least know the basics of PHP (variables, functions etc.)
What Is A PHP Class?
Good question. A PHP Class is nothing more then a bunch of functions, available in one location. Usually these functions do similar or related things.
An example would be a collection of car functions. One tells you how much gas you have, the other tells you how fast you’re going and another tells you how far you are from your destination.
Thats it! Not so scary is it? (you can put away your teddy-bear now)
What Is A PHP Object?
Ah, now this is where a lot of new PHP programmers get confused. Isn’t an object the same thing as a class? What the heck is the difference?
An Object is a copy of a Class. Think of a Class as a mold. Once you have the mold built, you can make as many copies as you want. I’ll say it again. An Object is a copy of a Class.
What Are Object Methods?
During your journey into PHP classes and objects, you may have come across the term “class method” or “object method”. What are these?
That’s easy too! A Method is nothing more then a function inside a class. When a function exists by itself, its called a function. When a function exits inside a class, its called a method.
What Does A Class Look Like?
As I said before, classes are collections of functions. Before we look at the structure of a class, lets create the car functions we discussed previously.
// Returns how much gas we have function check_gas() { $gas = 'Half Full'; return $gas; } // Returns how fast we're going function check_speed() { $speed = '100MPH'; return $speed; } // Returns the distance remaining function distance_remaining() { $distance = '20 Miles'; return $distance; }
As you can see, these functions are pretty straightforward. One obvious limitation is they aren’t very dynamic.
Now lets take a look at a class. When you create a class, you need to give it a name. Since we’re using a collection of car functions, we’ll call our class “Car”.
// Define our class as "Car" class Car { // Returns how much gas we have function check_gas() { $gas = 'Half Full'; return $gas; } // Returns how fast we're going function check_speed() { $speed = '100MPH'; return $speed; } // Returns the distance remaining function distance_remaining() { $distance = '20 Miles'; return $distance; } }
As you can see, all we’ve done is wrapped our car functions inside a class. A class is defined similar to a function. You start with “class” instead of “function” and remove the parenthesis “()”.
Creating Copies Of A Class
Before we continue, I should give you the technical term for creating copies of a class. Its called “Instantiation”. Fancy programmer jargon for “Copy”. To create an Object of a class, you “Instantiate” it. Glad that’s out the way.
So we’ve looked at how to create a class (our mold). How do we create copies of the mold? Well, its easier then you might think. Here’s how it’s done.
$CarObject = new Car();
As you can see, we’ve created a variable called $CarObject. We then gave it a value of new Car. The “new” keyword is how we create copies of a class. The new keyword is followed by the class we want to create a copy of, followed by parenthesis.
Lets say we had a class called Shoes.
class Shoes { // An empty class... }
We could create objects of it like this:
$Shoe1 = new Shoes(); $Shoe2 = new Shoes();
Using PHP Objects
Great, so now you’ve created a class called Car, and created an object from it. Now lets take a look at how to use it.
To call an objects methods, you use the variable name of the object, followed by a “->” and the method you want to call. Here’s what it looks like:
$MyCar = new Car(); // Create a new copy of the class $MyCar->check_gas(); // Call the check_gas() method
Simple huh?
Object Properties
As you may have noticed, our class is still very limited. All the values for our gas, speed and destination are hard-coded and can’t be changed. Lets make our class more dynamic by adding properties.
What are object properties? Object properties are variables that exists within the class. Object properties can be accessed from any of that objects methods or by the object its self.
To access a property from within the class, we use the “this” keyword.
Lets update our Car class to use properties.
class Car { $gas = 'Half Full'; $speed = '100MPH'; $distance = '20 Miles'; // Returns how much gas we have function check_gas() { return $this->gas; } // Returns how fast we're going function check_speed() { return $this->speed; } // Returns the distance remaining function distance_remaining() { return $this->distance; } }
We’ve moved the variables $gas, $speed and $distance out of their functions and into the class. These are now object properties.
The beauty of properties is when you update them, it effects the entire object. Lets try it now.
$Minivan = new Car(); // Create a new copy of our car class echo $Minivan->check_gas(); // Check the gas (outputs "Half Full") $Minivan->gas = "Empty!"; // Update our gas property echo $Minivan->check_gas(); // Check the gas again (outputs "Empty!");
See how easily we where able to check the gas, update it, and check it again? Now lets try it with multiple Car objects.
$Minivan = new Car(); $Truck = new Car(); echo $Minivan->check_gas(); // Half Full echo $Truck->check_gas(); // Half Full $Minivan->gas = "Empty!"; echo $Minivan->check_gas(); // Empty! echo $Truck->check_gas(); // Half Full
Notice that when we update the Minivan’s gas, it doesn’t effect the Truck. This as an important and powerful feature of objects. Changing one object will not effect the other.
Final Thoughts
You did it! You’ve created your own class, created copies of it, gave them properties and accessed their methods! You’re on your way to object-oriented leetness!
To wrap things up, we’ll quickly go over the concepts again.
- A class is a collection of functions
- An object is a copy of a class
- An method is a function inside a class
- An object property is a variable within the class
Try playing around with the Car class. Create a bunch of different objects, update the gas, speed and distance, then display them to the browser. Also try creating new methods that perform a new action. An example would be a method that turns the air-conditioning on and off.
You’ve learned a lot, but your still just scratching the surface. In the coming article, “A Beginners Guide To PHP Classes & Objects - Part 2″, I’ll show you how to really put your objects to work! Make sure to check back soon or subscribe to the RSS feed.
The Entire Class
Here’s the entire class we created throughout this tutorial. Save it in your favorite text editor and play around. If you get stuck, feel free to post your question in the comments!
// Define our class as "Car" class Car { $gas = 'Half Full'; $speed = '100MPH'; $distance = '20 Miles'; // Returns how much gas we have function check_gas() { return $this->gas; } // Returns how fast we're going function check_speed() { return $this->speed; } // Returns the distance remaining function distance_remaining() { return $this->distance; } } $Minivan = new Car(); $Truck = new Car(); echo $Minivan->check_gas(); // Half Full echo $Truck->check_gas(); // Half Full $Minivan->gas = "Empty!"; echo $Minivan->check_gas(); // Empty! echo $Truck->check_gas(); // Half Full
9.27.2008
ive been looking for an article like this, that would walk me through the entire process. all that class, object and property stuff really gets confusing fast.
a great article, thanks.
9.28.2008
Thanks for your article, this is very good article for beginners of PHP like me.
9.29.2008
Glad you both liked it. :)
I’m working on part 2 now. I’ll be going through scope and inheritance. Should have it done later this week.
10.07.2008
Really loved the article… I didn’t understand classes at all until I read this. Looking forward to part 2
10.22.2008
Thanks! I am now just looking for sessions and cookies
11.05.2008
I can’t wait for part 2, this was extremely helpful Thank YOU!!
11.08.2008
I just had to say thanx for this perfect explanation & intro to php object-oriented programming.
It is so easy to follow and well explained, that I feel I’ve actually learnt and understood object-oriented php for the first time.
Thanx
^_^
***Really looking forward to part 2!***
11.11.2008
Bookmarked!
if people dont understand this, programming is not for them.
Explained easily :)
11.27.2008
Excellent tutorial for classes in php.I`m expecting part2 soon.i`ll recommend this for “class” beginners.
Once again thanks for u r effort to teach us.
12.22.2008
Nice guide, before i started on classes i thought they were really advanced, but this showed me that its just a bunch of functions combined :)
so .. thanks for this, helped me alot :)
12.23.2008
Thanks for your article, this is very good article