PHP Object Oriented Programming for Newbies

This article analyzes the reasons of using Object Oriented Programming for PHP newcomers. In my opinion anyone can found thousands of tutorials for Object Oriented PHP and Object Oriented Programming. But what about a different… newbie PHP approach?

object-oriented-chaos

My approach is to convenience newcomers from PHP background to learn Object Oriented Programming. As there are plenty of tutorials out there, I will try to explain only some basic things about OO Programming with a simple way.

The only requirements to actually read this article is to have a very first impression of PHP. Even if the only thing that you have learned so far is:

<?php echo "hello World!"; ?>

You should still learn how to program with Object Oriented Programming. Crazy, huh? Why from using the simple functions in PHP we should learn to write code like the code below?

namespace Foo\Bar {
    class Baz implements BamAwareInterface {
        public $bam;
        public function setBam(Bam $bam){
            $this->bam = $bam;
        }
    }
    class Bam {
    }
    interface BamAwareInterface
    {
        public function setBam(Bam $bam);
    }
}

Well let’s start then…

The paradox

I have many years experience in Object Oriented programming with PHP but with Java as well. I remember my very first approach at the university with Object Oriented Programming and Java. They didn’t teach us WHY to use Object Oriented programming, they just teach us that THIS is Object Oriented Programming and some ways that we can use it.

The paradox about that is that from the basic steps of programming you need to jump to Object Oriented programming. It was for me like learning addition in Math and then jump straight away to rocket science! So this was my first experience about Object Oriented programming. I was using 4 years object oriented programming in Java but I couldn’t understand what was the real reason to use it. For me it was just a necessary evil to learn it as in my mind it was something that I HAD to write in order to get the expected results.

I can give you a simple example. The very basic example that I’ve started with in Java was:

public class Root {
    public static void main(String[] args) {
        System.out.print("Hello World\n");
    }
}

The problem here is that I don’t need all of these and I didn’t even know what the “class” was or what the “public” or what the “static” or what the “void” means… . The only thing that I wanted to do is to have a very first “Hello World” in my screen. So I just copy-paste the class with the unknown public static void main(String[] args) { in order to make it work!!

Hey wait! Are we talking about Java or PHP?

Don’t worry we are getting there…

In PHP the same example, can be easily written like this:

<?php print "Hello World!";

And with this code I can straight away understand that “<?php” is to start php code. Easy to remember and next time I will not have to copy my previous code in order to print something on my screen. It is bad to copy something without knowing and understanding the reason that this is there. What I am trying to say is that it is always better to start USING classes only when you REALLY know what they are doing.

Why OO Programming?

PHP gives us the opportunity to not use Object Oriented Programming if we don’t really need it. This is very cool as Beginners can create a whole website without using any object. So why to use Object Oriented Programming?

It took me 2 years to actually realize the power of Object Oriented Programming! Of course while you are now reading this article you will think that I have a comprehension problem. Although this is not the case! At the very first moment when I started learning why to use Object Oriented Programming, I understood it pretty well. I understood pretty well that your code can be much more extendable and testable and lot of more things like that. However to actually REALIZE the importance of Object Oriented Programming needs time and lot of practice. In the real world (especially at work… world) things are different. In the real world the business only cares for the actual results that our code is rendering. When we are coding the only thing that we have in mind is “How can I get the expected results with the fastest possible way?”. This is the wrong way to think and I will prove it with an example.

So let’s start with a very basic page in PHP. Let’s say that we want to show the user’s first name and last name when he/she firsts login. Also let’s say that there is lot of pressure at the office and this need to be ready… now πŸ™‚ .

Our first attempt is without using objects at all.

<?php
$con = mysqli_connect("example.com","peter","abc123","my_db");

if (mysqli_connect_errno($con)) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '". mysqli_real_escape_string($_GET['user_id'])."'");

$row = mysqli_fetch_array($result)

echo "<div>";
echo $row['first_name'] . " " . $row['last_name'];
echo "</div>";

mysqli_close($con);
?>

So with the above example our request is done. So as for the request. “I want you to show me the first and last name when the user firsts logged in.” , it is done! Your boss is very proud of your work. You are very proud as this was really easy and it was really fast as well. Moreover as we don’t have a big experience with coding, we are happy that the results are actually showing at the screen.

This is a completely wrong way to think though. Your code isn’t there to be executed only once. This code will be executed now and it will be there in the future (your code lifetime can be 4 months, 1 year… maybe 10 years!). So at one point this code need to change. So your code will never actually be exactly the same for ever. So for this specific example, we can see there is only one situation that the User’s first name and last name will appear. Only if we have the user_id at the URL as a GET parameter. So let’s say that we revisited our code after 1 month. Customer saw that user’s where adding URL’s like http://www.example.com?user_id={random_id} and they where looking the first and last name of other users at the website. Also we realized that we don’t only need to show the first name and last name once but we want to show it everytime (e.g. with a session) when a user is logged in.

One month later you see your own code and you don’t remember what you had done so you start reading again your code line by line.. So as we can see it was fast at the beginning but it is not so fast now that you are searching all your code to check where to change your $_GET[‘user_id’] with $_SESSION[‘user_id’] . Your code is not readable and you are changing your whole code again and again with each request. Some requests can come later like “We want when the user is not logged in to show a button ‘Register’ and redirect him to a registration page.”, “We want to add the email of the user as well so it will be: John Smith (john@smith.com)” , “As this functionality is working well we need to implement it to our back-office as well”… .e.t.c. As you can see lot of small changes can happen but with the above code one thing is for sure. You will always read all of your code to understand what is going on and the tasks will getting more difficult and more difficult. A small example about a messy code that I have in mind is the below:

<?php
$con = mysqli_connect("example.com","peter","abc123","my_db");

if (mysqli_connect_errno($con)) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if (isset($_GET['user_id'])) {
	$result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '". mysqli_real_escape_string($_GET['user_id'])."'");
}elseif (isset($_SESSION['user_id'])) {
	$result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '". mysqli_real_escape_string($_SESSION['user_id'])."'");
}

if (!isset($result)) {
	$row = mysqli_fetch_array($result)

	echo "<div>";
	echo $row['first_name'] . " " . $row['last_name']." (".$row['email'].")";
	echo "</div>";
} else {
	echo "<form action="/register-form.php"><button>Register</button></form>";
}
mysqli_close($con);
?>

Your code is already a mess. It is difficult to do any change. It is difficult to understand what is going on and you can easily do mistakes.

Objects for the Rescue!

So now that we have a very first impression of our request, let’s re-create our example from scratch!

I will try to explain as less as possible for the object interfaces… e.t.c. as this is not the purpose of this article.

Let’s see our final re-make of our code with OO programming.

//Get User's info by the userID
$user_info = User::getUserInfoById($user_id);

//Render data to the View
$view = new View();
$view->user_info = $user_info;

$view->render('user_details');

As you can see your code is now much more readable (That’s 1). We can now read it and add some automated tests to our Objects as well (That’s 2). Many people may ask where the rest code gone? Where is the database connection, where is the redirection, where is the $user_id is coming from? This doesn’t really matters as it is happening at a separate place of the code. Probably a different file. And this is one more thing that OO Programming is offering to you, you separate your code to different files and you can have a better structure of your code (That’s 3). For example we have different file for Presentation (View), different file for database connection (config) and different file for our business logic (Controller). One more thing that OO Programing is offering is the Don’t Repeat YourSelf (DRY) principle (That’s 4). And once you have all the good benefits of OO Programming your gift is that your code will be extendable for the future (That’s 5)

People may thing that objects are bad! They are complex, they are confusing and they are hard to learn. I am sorry people but that’s wrong! Objects are good for anyone! Many people think that Objects are evil and they are trying to make our life harder. Convince yourself that Objects are Angels that trying to save you from long term problems . It will save your time and effort. Objects Oriented programming is like Batman in Gotham City… many people think that he is evil, but he is always there to save you from the bad people (in our case bad coding πŸ™‚ ).

object oriented for the rescue

So let’s have a summary:
1. Your code will be more readable.
2. Your code is testable (for example you can use automated tests like PHPUnit)
3. Your code will have a better structure.
4. You will follow the DRY principle at your code (and this will make you proud)
5. Your code will be extendable for the future.

Now in my opinion few more things that OO can help is:
6. You can get a better quality job if you know OO Programming as business will understand the difference.
7. You can be more proud of yourself when you are coding.
8. You can communicate with other developers in all around the world more easy.

There are plenty of other benefits that OO programing is offering. This article is pointing only few of them.

You convinced me, what is the next step?

If you are really interested about OO Programming in PHP, you can learn more by reading this article . It is a very good start and it has lot of examples.

Once you are done with learning OO Programming, you can start using an MVC PHP Framework for your project. Don’t be afraid to start using them. They are lot of them out there and it doesn’t take a big effort to install them! Here is a list of the most famous ones (starting from the simplest one):
Codeigniter
CakePHP
Yii
Laravel
Symfony
Zend Framework

Want to learn even more? You want to learn the real OO design principles and why everything your boss told you about inheritance might be wrong (and what to do instead)? Head First Design Patterns is the the book that made me realize the power of OO Design Patterns. Why don’t you give a try?

I hope you will enjoy OO Programing as much as I do. Any comments or suggestions are always welcome. Happy coding πŸ™‚

← Previous post

Next post →

20 Comments

  1. Bigtt76

    You like beer a lot πŸ˜€

  2. Petros K

    Awesome topic!

  3. Sapana Biju

    Superb! Have to learn OOPS, MVC????

  4. superb…interesting topic…

  5. Thanks a lot men for this informative article !!

  6. Ankur Lakhani

    Very Good Article.But i have a query that after knowing the very basics of objects and classes as explained in the article suggested by you,how to move ahead to be really able to develop a website as we are doing using the procedural way?
    Waiting for your reply
    Thanks.

    • web_and_development

      Hello there and I am really glad that you did like the article πŸ™‚

      That’s a good question actually. Well the only thing that you need to do is to learn while you are coding. This is the only way to actually learn. So my suggestion is: Try to learn a PHP framework to begin with. I suggest Laravel. And then you will actually learn Object Oriented Programming while you are coding πŸ™‚ . The good thing about Laravel is that it uses good coding practices and I think it will be very useful for you to learn the power of objects.

      Just remember, you are learning OO Programming only once and then you can use the same coding structure to almost every language out-there πŸ™‚ http://en.wikipedia.org/wiki/List_of_object-oriented_programming_languages

      The secret here is: Don’t be scared to use them. It will make your life easier for sure. It is always difficult at the beginning to understand the power of Objects, but believe me it worth the time.

      I hope that helped

      Regards
      Johnny

  7. Ankur Lakhani

    Thankyou so much for the guidance.it is really important tome.

    But
    actually my problem is that,there being so many options,i am confused
    how to move ahead.i started with basic php mysql and also developed 2-3
    simple websites only involving simple form submission and retrieving the
    data at some place.thats it.

    Then i tried using wordpress but i
    was merely able to modify a theme as per requirement without using any
    programming itself.But then as i was not able to tackle complex
    requirements,i left it(not able to understand hooks).

    Then,i
    started for object oriented PHP,learned the very basics from your
    article and now again stuck.Actually i am wondering would i be able to
    learn laravel without any OOP background i PHP??
    And if yes,can you please suggest the best way to learn it..i.e.a good website or a book to learn laravel.

    Thanks Again

    • web_and_development

      Hey, you can start with the book: https://leanpub.com/laravel4documentation for laravel. This is a free book actually so you will not have to pay anything for your first book.

      Have a look at this thread, I think it will solve all of your questions http://forumsarchive.laravel.io/viewtopic.php?id=13411

      For me, the answer is simple. YES, you can learn Laravel without any OOP background in PHP. The framework will actually teach you how and why to use Objects. If though you believe that you don’t have enough time to start learning a brand new framework, I would suggest that you can start using OO PHP in your already existing project (simple PHP, no frameworks). If you have a simple PHP website with simple forms… e.t.c. try to organize your code better, try to create sub-folders for db connections… e.t.c. Then try to do it with Object Oriented Programming. After this trip you will actually realize that you just need a PHP framework πŸ™‚

      If however you don’t have enough time, you can start learning Codeigniter that it is really simple. Just install it and start searching in google and stackoverflow your answers πŸ™‚ . Pretty simple isn’t it? Codeigniter will not actually teach you the best way to do things, but at least you will learn a simple MVC framework . A good book for Codeigniter (I am an official reviewer of this book by the way πŸ˜‰ ) is the: http://www.packtpub.com/codeigniter-2-cookbook/book . But make sure that you will be familial with PHP before buying this book. “CodeIgniter 2 Cookbook is for intermediate to advanced PHP developers
      who want to begin using the powerful CodeIgniter framework to create web
      applications. Familiarity with CodeIgniter isn’t essential, but it will
      be useful if you have been introduced to the framework before.”

      So as a summary, my suggestion is:
      – Learn Object Oriented programming with simple PHP (no frameworks)
      – Use your first PHP framework. Codeigniter or Laravel (see why http://www.vladstudio.com/fr/post/?laravel—a-beautiful-php-framework-that-does-not-make-me-feel-stupid )

      • Ankur Lakhani

        Thankyou for your help and time again.

        So,now first i’ll use objected oriented programming with simple PHP in my work.Then i’ll head over to laravel.right?

        So as per your first summary i tried and used the OOP way of connecting to database and similar as per
        this article.

        My Code:http://snipplr.com/view/74010/php-form-handling/

        By viewing my code,u would actually understand what and where i am lacking.i am not able to figure out that apart from database connection and like,what else can i change to make it the OOP way,i.e.how and where should i use the classes that i learned in basics.In short,how can i completely use OOP in my code.Is there any website with the tutorials as on google i only find the basics,but how to move ahead the OOP way,thats the problem.

        Thanks.

        • web_and_development

          Hello there,

          Ok, so as I can understand from your level of PHP I think that Laravel may be a bit confusing for you at the beginning . So it is better to start with Codeigniter.

          What you can actually do to make it with a more proper way is to use an OO framework like Codeigniter.

          So try this. Try to have the exact same code with Codeigniter.

          So if you learn Codeigniter at first, you will understand that everything has their own place. For example in your code, you will not need to include the database connection anymore. Or you will not need the session to be loaded like that. The view will be in separate file… e.t.c.

          By learning codeigniter you will see that everything is based on OO programming. So your next step is:
          – Try to do the exact same thing that you did with your code: http://snipplr.com/view/74010/php-form-handling/ but with Codeigniter and the Codeigniter features. For example: – database connection, sessions, queries, views… e.t.c. If you have any questions then search it in stackoverflow. You have to learn it by your own and spend a lot of time to do it better and better. I can just give you some advices that’s all.

          If you want to have a review at your code at the end, you can go to: http://codereview.stackexchange.com/ and copy your code with some description with what you try to achieve and you will have all of your answers there πŸ™‚

          Pretty cool isn’t?

          Regards
          Johnny

          • Ankur Lakhani

            Thankyou so much for the kind advice.And sorry for bothering you so much like this.i will soon start to use codeignitor after learning it from a proper source and stackoverflow for the queries…Hope it goes well.

  8. Grocery CRUD brought me here – thanks for that – which I found when I was looking for a Django replacement in the PHP world.

    I started with PHP some 20 years ago, programming a forum application,
    but only using functions not objects, what PHP 3 didn’t even offer at
    the time. Later I began to work with objects, and I saw the
    advantage mainly in the way varibales are handled and encapsulated.
    Chances are I did not really grasp the OO way until now.

    From this article, most arguments for OO programming are also valid for
    functions – code reuse, better overview, separate files for seperate
    tasks etc.
    So from your point of view – what is the special advantage of using classes and objects instead of a self-grown function library?

    • web_and_development

      Basically there are many many reasons why to use OO programming.I think however the most IMPORTANT advantage of using a good structure of classes and objects is mainly this:

      Your code can be automatically been tested.

      Imagine a world where you can have 1000 of tests in just 1 second! This is now possible with unit tests. And this is very hard if your code is not in a well structured Object Oriented way.

      I am doing some training in work and basically I am repeating all the time: “Your actual real world testing can now only take you 5 minutes at the end of the day if you have a good structured code. Let the complicated tests for the unit tests πŸ™‚

      • Interesting aspect, seems I have not yet experienced the merits of unit testing.
        Only in the Django world I found the error messages much less telling than in PHP, so more time was needed for debugging.
        But that might not be connected to the OO strategy.

  9. kadirarli

    Thank you for good article.

  10. Sandbird

    I love it when people say “that’s for another time.Β¨ or “this doesn’t matter right now” when it comes to the actual code inside the class that does all the work for your 4 line preview.
    Of course it matters. why would I write 1000 lines of code in a class to just create a simple contact form, when I can do the same with functions and parameters with much less code.
    Sometimes php frameworks like codeigniter when it comes to simple things you have to edit/create 3-4 files and break your code, instead of a simple php file.
    Not mention all the piano lessons you have to do first to get used to the Ctrl+Tabing to switch between the files since now your contact form has 1 file for the .js, one for the form, one for the actual php queries and stuff and probably one for the menu hooks, actions and what not.
    I started reading this article with an open mind, only to once again read the same type of useless info….”it’s not important right now”. At least all you guys who think it’s not important send us an email when you figure out when it is so we can finally figure out it we should spent 100000 hours of our time figuring if our site should be done with codeigniter or simple functions.

    • web_and_development

      Hello @sandbird:disqus and that’s why I did create this article.
      Just to make it more clear to people that are reading this. Questions like:
      – Is it ok to not use OO because I don’t like it? That’s completely fine!
      – Am I a bad developer if I don’t know OO? No you are not!
      – Can I still create big applications without using OO programming? Yes definitely you can!

      However, the OO programming is mainly a pattern to ORGANISE you better. You did mention the Ctrl+Tabbing. Now this is not required with the newest editors (e.g. PHPStorm) as you can click into the function and see a preview of what it is doing.

      The reason creating this article is to answer you the question of WHY to use OO programming and not HOW (that’s why I have other articles as reference).

      So questions like the below is hard to answer them without using OO programming:
      – Can I work with a team of 10 people without using OO programming at the same project? Errrr, it is very difficult (if not impossible) as the same file will always have too many conflicts. If you’ve worked with more than 3 people at the same project you definitely know what I mean.
      – Can I use unit-tests with only using functions? Yes, you can… theoretically! But practically how you will mock some data (e.g. create different types of testing to test your functions?) Is everything going to be as a parameter? It will make your life harder and yes… you will write 100000 lines of code there in order to make it work.

      And lastly about the 100000 hours of spending about using frameworks, yes this is not always the best thing. HOWEVER spending time to learn OO programming is a very very good investment as this is like a common communication between developers in all the languages. For example the book: Design Patterns: Elements of Reusable Object-Oriented Software was published in 1994!!! So it is definitely worth learning it as it is something standard that at least for the next 10 years will not change.

      As a summary I want people to understand more the benefits of OO programming rather than force them using them.

      • Balram Maurya

        nice post and nicer coment. now i understand why use OOP. thank you for this great post. now i am clear that i must learn OOP.

  11. Aj Costelo

    This… this gives me motivation! πŸ™‚