Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

An Introduction to Object Oriented PHP – Part 1

An Introduction to Object Oriented PHP – Part 1

About This Series

This is a three part series introducing Object-Oriented PHP, a way to manage your code and keep different parts separate, all while being easily accessible. I hadn’t really planned it this way, but my previous article works as a great precursor to this article, showing you how to get a PHP/MySQL Sandbox up and running, which is just what we’ll be using for this tutorial as I believe a hands-on approach is the best way to learn things like this.

By the end of this series, we are going to make a very simple MySQLi (MySQL Improved) database interaction class, for doing common tasks.

In this Tutorial

Today, we are going to learn the following:

  1. What the heck are Objects and Classes?
  2. Writing our first class
  3. How to use your freshly written class
  4. How to personalize it

Let’s get started!

What the heck are Objects and Classes?

Classes, at their simplest point, are just receptacles of functions. They can be compared to a folder on your computer (assuming you aren’t running DOS). Inside the folder you may have three files, or in this case, functions. Let’s use a classic example, a Dog.

Take a look at the following image:

A Canine Example

As you can see, a Dog has many “functions”. It can run, walk, sit, play, and bark. This is the essence of what a class is.

An Object, on the other hand, is a way to represent your class. For example, you can have your class named “Dog”, but you can reference it by a variable called Cat if you really wanted to confuse yourself.

That’s all we’re going to cover in this section, so if you’re still confused, read on and I believe the examples will make some coherent sense.

Writing our first class

Since this is just our first class, we’re going to keep things nice and simple. Open up your text editor of choice and make a new file in your web root called myClass.php. Add in the following code:

<?php
class myClass
{
	function sayHello()
	{
		echo "Hello there!";
	}
}
?>

If you navigate to this file on your server, nothing will show up. All we did was set up a class (container) and add in a function, we never referenced it to be run.

How to use your freshly written class

Now that we have our myClass.php file all written, we’re going to reference it and use it. Make a new file in the same folder as your class is in, called index.php. Add in the following code:

<?php

	require_once('myClass.php');

	$myClass = new myClass();

	$myClass->sayHello();

?>

If you run the file, you should see “Hello World!” echoed out. Let’s go over what we did to make this work. First, you can see that we required the myClass.php file, which contains our container full of functions. Next, we had to make a new Object, and we used the class name as the object name, just for ease of use. And finally, we referenced our sayHello function by writing the Object name with an arrow and the function name.

Making it Friendlier

Right now, if we wanted to use this to greet a logged in user, there wouldn’t be much of a sense of personalization, would there? Wouldn’t it be nice if we could say Hello to the specific user? Well, we can! Go back to your myClass.php file and edit it accordingly:

<?php
class myClass
{
	function sayHello($user)
	{
		echo "Hello " . $user . "!";
	}
}
?>

All we did was add a parameter to the function called name, that we can pass along to the function from our index file. Go back to your index.php file now and add your name like so:

<?php

	require_once('myClass.php');

	$myClass = new myClass();

	$myClass->sayHello('Dixon');

?>

Now, reload your index.php file and you should see a nice textual greeting!

Conclusion

Now that we’ve covered the very basics of Object-Oriented PHP, you can practically do it all. And was it hard? Hopefully not! Be sure to check in later for the rest of this series, in which we’ll be making a fully functional MySQLi Database interaction class! Thanks for reading.

Interested in writing a guest post for us like Dixon? We’d love to have you! Here’s how to get started.

Wordpress.com stats not installed! Posted Wednesday, July 15th, 2009 / Back to Top

I this post. Tweet
SPONSOR

36 Comments 26 Mentions

  1. Henry Author Editor

    Cool! Looking forward for the next tutorials. One thing. In the class Dog you have the function “run” twice in the image your showing the example. No big deal though. :)
    .-= Henry´s last blog ..100+ Fascinating Eco Friendly Logos =-.

    July 15, 2009 · Reply

  2. Zach Dunn Author Editor

    @Henry

    Thanks for the heads up, I’ve uploaded the update image.

    July 15, 2009 · Reply

  3. Henry Author Editor

    No problem. Keep up the great work!
    .-= Henry´s last blog ..Daily Creative Inspiration #14 =-.

    July 15, 2009 · Reply

  4. Randy Federighi Author Editor

    Great timing. Glad I have you on my iGoogle home page. Been wanting to grasp oop.

    July 15, 2009 · Reply

  5. Cristian Author Editor

    Lovely post, always nice to open with a simple example for people to get their heads around.

    (Side note, this font and footer links font is almost impossible to read in FF on my machine.) Screenshot @ http://img174.imageshack.us/img174/4848/buildinternetscreenshot.jpg

    July 16, 2009 · Reply

  6. Vince Author Editor

    Great article, I really need to get into OOP for my webapps.
    .-= Vince´s last blog ..Webdesign proces BTI Foundation =-.

    July 16, 2009 · Reply

  7. Zach Dunn Author Editor

    @Christian

    That appears to be more of a browser end display problem. Do you have anti-aliasing on?

    July 16, 2009 · Reply

  8. Mike Author Editor

    Hey, thanks for the tut, I’ve been just trying to learn OOP in c++ and it’s nice to compare it to PHP.

    Looking forward for the next part, Mike.

    July 16, 2009 · Reply

  9. Alejandro Author Editor

    Thanks for the post. Pretty useful for me right now :)

    July 16, 2009 · Reply

  10. Paul Author Editor

    One of the best beginner OPP tuts I seen. Nice job.
    .-= Paul´s last blog ..Display the number of followers you have on Twitter the easy way. With Twitter API XML and PHP. =-.

    July 16, 2009 · Reply

  11. Jeroen Author Editor

    Thanks, keep on writing like this, and I’ll keep following! :)

    July 17, 2009 · Reply

  12. Cristian Author Editor

    @Zach I’ve played with some settings, its a lot better but still a little blurry. This is my work machine though. Keep up the good work :-)

    July 17, 2009 · Reply

  13. Eddie Author Editor

    Waiting for the next one!!!

    July 17, 2009 · Reply

  14. Montana Flynn Author Editor

    It would be nice to see how to have multiple functions in one class, like your dog example. Anyways, great post! What do you think of my blog re-design?
    .-= Montana Flynn´s last blog ..PRESS the G8 against poverty: Best Design of the week =-.

    July 17, 2009 · Reply

  15. Dixon Crews Author Editor

    @Montana – Yes yes, all for the next tutorials!

    July 17, 2009 · Reply

  16. Markus Thömmes Author Editor

    Very nice. I wanted such a simple walktrough for a very long time now. Go on with part 2 :).
    .-= Markus Thömmes´s last blog ..Workflow: Enso Launcher =-.

    July 18, 2009 · Reply

  17. Derrick Author Editor

    You may want to clarify and elaborate more on the difference between a class and an object. That seems to be the most popular question that I’m asked by OOP newcomers. When I explain it, I usually compare classes to blueprints, with objects being the buildings created using those blueprints. Just a suggestion :)

    July 18, 2009 · Reply

  18. sunjester Author Editor

    that cool and all but why are you still using wordpress?

    July 19, 2009 · Reply

  19. Sam Dunn Author Editor

    @sunjester
    I don’t think using WordPress is a negative thing at all. The community is developed and there is a lot of support/plugins. It’s a matter of not reinventing the wheel and saving time to contribute fresh things to the internet. I’m curious what alternative you would use?

    July 19, 2009 · Reply

  20. J. Pedro Ribeiro Author Editor

    OOPHP is indeed a powerful approach, I’ll be looking forward to the next posts to see how deep you go on this subject. Cheers!

    July 19, 2009 · Reply

  21. MCB Web Design, Newcastle Author Editor

    Why the hate for WordPress? I find it a solid platform for basic post-based sites, including this one.

    July 20, 2009 · Reply

  22. sunjester Author Editor

    Exactly, everyone wants to be “cool”, so instead of putting in work and making original software we have to visit site after site of the same layout of the same software.

    i say if your gonna write tutorials about OOP maybe you should write software that uses OOP.

    July 22, 2009 · Reply

  23. Dixon Crews Author Editor

    “i say if your gonna write tutorials about OOP maybe you should write software that uses OOP.”

    Is that directed at me?
    .-= Dixon Crews´s last blog ..dixoncrews: I love Google Docs. =-.

    July 22, 2009 · Reply

  24. Sam Dunn Author Editor

    @sunjester
    It’s not a matter of being cool, it’s a matter of being smart with your time. The point is that WordPress is a very functional and widely accepted solution, I think you’ll be hard pressed to find others that share your sentiment.
    I would rather spend my time making new content than reinventing something that already exists.

    July 23, 2009 · Reply

  25. Flex developer Author Editor

    I agree with MCB Web Design that WP one of the best platform. I use WP and very happy.

    July 23, 2009 · Reply

  26. chichibek Author Editor

    gracias por el articulo, porfavor continuen con el y de esta manera, gracias desde centro america

    July 29, 2009 · Reply

  27. Jim Westergren Author Editor

    Thanks a lot for this – just what I needed for my next step of PHP learning.
    .-= Jim Westergren´s last blog ..Version 2 of my CMS, The Clesto CMS =-.

    October 5, 2009 · Reply

  28. Maicon Sobczak Author Editor

    Very useful. I will start my studies with this post.

    December 3, 2009 · Reply

  29. Anon Author Editor

    Your definition of an object is incorrect (or at the very least, vague).

    An object is defined as an INSTANCE of a class.

    December 28, 2009 · Reply

  30. Classical Electric Guitar Author Editor

    Great weblog. We obtained a lot excellent data. I a watch on this technology for awhile. It’s intriguing how this keeps varying, yet some of the primary elements stay the actual same. Have you observed much alter since Google created their own latest acquisition in the field?

    May 19, 2010 · Reply

  31. Sz Author Editor

    Finally I got it ! Thanks

    July 19, 2010 · Reply

  32. matkavakuutus Author Editor

    was very encouraged to find this site. I wanted to thank you for this special read. I definitely savored every little bit of it and I have you bookmarked to check out new stuff you post.

    August 11, 2010 · Reply

  33. cheap and original sheepskin boots Author Editor

    What you’re saying is completely true. I know that everybody must say the same thing, but I just think that you put it in a way that everyone can understand. I also love the images you put in here. They fit so well with what you’re trying to say. I’m sure you’ll reach so many people with what you’ve got to say.

    August 24, 2010 · Reply

  34. gite de france Author Editor

    Thanks,

    This is a great article and a great website. I liked it very much. It will help me to optimise my websites in europe. I have website in travel and that meens a lot of seo work !!

    Thanks a lot and greetings,

    Stephen

    August 28, 2010 · Reply

  35. ashish Author Editor

    thanx,nice article, really its helps me to start oophp.

    February 21, 2012 · Reply

  36. Amit Ramachandran Author Editor

    Nice post. Really help me to discover in depth. I got in depth replica of this tutorial on http://www.techflirt.com/tutorials/oop-in-php/index.html

    This guy has explained things in very detail. But you need basic knowledge of oop before it.

    March 29, 2013 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2012 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top