An Introduction to Object Oriented PHP – Part 1

An Introduction to Object Oriented PHP

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.

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Dixon Crews

Hey, I'm a 15 year old high school student who really loves web design and development from North Carolina, US. I'd love to go to school to learn even more about design, possibly computer science, and eventually having a job designing and developing websites! Follow Dixon on Twitter.

 

Discussion

  1. Henry

    July 15th, 2009 at 8:15 PM

    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 =-.

  2. Zach Dunn

    July 15th, 2009 at 8:37 PM

    @Henry

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

  3. Henry

    July 15th, 2009 at 11:43 PM

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

  4. Randy Federighi

    July 15th, 2009 at 11:46 PM

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

  5. Cristian

    July 16th, 2009 at 4:07 AM

    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

  6. Vince

    July 16th, 2009 at 4:46 AM

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

  7. Zach Dunn

    July 16th, 2009 at 9:17 AM

    @Christian

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

  8. Mike

    July 16th, 2009 at 10:46 AM

    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.

  9. Alejandro

    July 16th, 2009 at 4:21 PM

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

  10. Paul

    July 16th, 2009 at 7:28 PM

    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. =-.

  11. Jeroen

    July 17th, 2009 at 5:14 AM

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

  12. Cristian

    July 17th, 2009 at 9:39 AM

    @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 :-)

  13. Eddie

    July 17th, 2009 at 6:23 PM

    Waiting for the next one!!!

  14. Montana Flynn

    July 17th, 2009 at 7:01 PM

    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 =-.

  15. Dixon Crews

    July 17th, 2009 at 7:51 PM

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

  16. Markus Thömmes

    July 18th, 2009 at 11:45 AM

    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 =-.

  17. Derrick

    July 18th, 2009 at 10:15 PM

    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 :)

  18. sunjester

    July 19th, 2009 at 9:25 AM

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

  19. Sam Dunn

    July 19th, 2009 at 9:35 AM

    @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?

  20. J. Pedro Ribeiro

    July 19th, 2009 at 1:46 PM

    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!

  21. MCB Web Design, Newcastle

    July 20th, 2009 at 4:46 AM

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

  22. sunjester

    July 22nd, 2009 at 2:16 AM

    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.

  23. Dixon Crews

    July 22nd, 2009 at 4:34 PM

    “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. =-.

  24. Sam Dunn

    July 23rd, 2009 at 1:59 AM

    @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.

  25. Flex developer

    July 23rd, 2009 at 9:09 AM

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

  26. chichibek

    July 29th, 2009 at 5:38 PM

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

  27. Jim Westergren

    October 5th, 2009 at 7:25 AM

    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 =-.

  28. Maicon Sobczak

    December 3rd, 2009 at 11:11 AM

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

  29. Anon

    December 28th, 2009 at 10:08 PM

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

    An object is defined as an INSTANCE of a class.

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!