12

I've been writing PHP for about six years now and have got to a point where I feel I should be doing more to write better code. I know that Object Oriented code is the way to go but I can't get my head around the concept.

Can anyone explain in terms that any idiot can understand, OO and how it works in PHP or point me to an idiots guide tutorial?

Rubén
  • 34,714
  • 9
  • 70
  • 166
hellweaver666
  • 343
  • 2
  • 10
  • 1
    I know exactly what you mean... just read a lot and immerse yourself in it and it will come slowly but surely :) – alex Dec 02 '08 at 02:00
  • see also: http://stackoverflow.com/questions/1530868/simple-explanation-php-oop-vs-procedural – dreftymac Oct 26 '11 at 18:09
  • To ask for an explanation of OO in one post is too general; and this site is not intended for tutorial requests. – Keith Pinson Feb 06 '13 at 17:28

7 Answers7

34

Think of a thingy. Any thingy, a thingy you want to do stuff to. Say, a breakfast.

(All code is pseudocode, any resemblance to any language living, dead, or being clinically abused in the banking industry is entirely coincidental and nothing to do with your post being tagged PHP)

So you define a template for how you'd represent a breakfast. This is a class:

class Breakfast {

}

Breakfasts contain attributes. In normal non-object-oriented stuff, you might use an array for this:

$breakfast = array(
'toast_slices' => 2,
'eggs' => 2,
'egg_type' => 'fried',
'beans' => 'Hell yeah',
'bacon_rashers' => 3 
);

And you'd have various functions for fiddling with it:

function does_user_want_beans($breakfast){
     if (isset($breakfast['beans']) && $breakfast['beans'] != 'Hell no'){
         return true;
     }
     return false;
}

And you've got a mess, and not just because of the beans. You've got a data structure that programmers can screw with at will, an ever-expanding collection of functions to do with the breakfast entirely divorced from the definition of the data. So instead, you might do this:

class Breakfast {
  var $toast_slices = 2;
  var $eggs = 2;
  var $egg_type = 'fried';
  var $beans = 'Hell yeah';
  var $bacon_rashers = 3;

  function wants_beans(){

     if (isset($this->beans) && $this->beans != 'Hell no'){
         return true;
     }

     return true;

  }

  function moar_magic_pig($amount = 1){

     $this->bacon += $amount;

  }

  function cook(){
      breakfast_cook($this);
  }

}

And then manipulating the program's idea of Breakfast becomes a lot cleaner:

$users = fetch_list_of_users();

foreach ($users as $user){
    // So this creates an instance of the Breakfast template we defined above

    $breakfast = new Breakfast(); 

    if ($user->likesBacon){
       $breakfast->moar_magic_pig(4);
    }

    // If you find a PECL module that does this, Email me.
    $breakfast->cook();
}

I think this looks cleaner, and a far neater way of representing blobs of data we want to treat as a consistent object.

There are better explanations of what OO actually is, and why it's academically better, but this is my practical reason, and it contains bacon.

joshuahedlund
  • 1,722
  • 2
  • 20
  • 25
Aquarion
  • 341
  • 2
  • 3
  • "Academically better?" All programming paradigms are different and some are better in different places, but to say OOP is academically better than procedural (or functional) is not fair. OOP makes it much harder for data to be abstracted from their methods, for instance – Daniel Papasian Sep 18 '08 at 16:39
  • FLYING MAGIC STUFFS ON A PLATE FOR BREAKFAST! +1 – Kent Fredric Dec 10 '08 at 13:27
  • 1
    I really like your explanation and example, I just want to point out an accidental ">" in the line where you assign bacon_rashers. That throws off the coloring. There's also an extra ' in the line above it. (I'm only trying to help, for people who come later to see this, like me). Again, thank you for such a great example! – Paul Hoffer Jul 13 '10 at 07:11
7

A warning is at place: you won't learn OO programming without learning OO design! The key concept is to define the functions operating on your data together with the appropriate data. Then you can tell your objects what to do, without having to query their contents.

Surely take a look at the "Tell, don't Ask" philosophy, and the "Need to know" principle (aka the "Law of Demeter") is a very important one, too.

xtofl
  • 40,723
  • 12
  • 105
  • 192
6

Some of the key reasons to use OO are to structure code in a similar way to how we humans like to perceive and relate to things, and exploit the benefits of economy, maintainability, reliability, and scalability.

i.e: Humankind designed the wheel thousands of years ago. We may refine it all the time, but we certainly don't need to be re-inventing it again....

1) We like to categorise things: "this one's bigger than this one", "this one costs more than that one", "this one is almost the same as that one".

2) We like to simplify things: "OK, it's a V8 liquid cooled turbo driven tractor, but I still just turn the steering wheel and press my feet on the peddles to drive it, right?".

3) We like to standardise things: "OK, let's call triangles, circles, and squares all SHAPES, and expect them all to have an AREA and a CIRCUMFERENCE".

4) We like to adapt things: "hmmm, I like that, but can I have it in Racing Green instead?".

5) We like to create blueprints: "I haven't got the time or money (or approval) to build that yet, but it WILL have a door and a roof, and some windows, and walls".

6) We like to protect things: "OK, I'll let you see the total price, but I'm hiding the mark-up I added from you!".

7) We like things to communicate with each other: "I want to access my bank balance through: my mobile; my computer; an ATM; a bank employee; etc..".

To learn how to exploit OO (and see some of the advantages) then I suggest you set yourself an exercise as homework - maybe a browser based application that deals with SHAPES such as circles, rectangles, and triangles, and keeps track of their area, colour, position, and z-index etc. Then add squares as a special case of rectangle since it is the same in respect to most of it's definition, area, etc. Just has the added condition where the height is the same as the width. To make it harder then you could make a rectangle a type of quadrangle which is a type of polygon. etc. etc.

NOTE: I wouldn't start using a PHP Framework until you are comfortable with the basics of OO programming first. They are much more powerful when you can extend classes of your own and if you can't then it's a bit like learning something by rote -> much harder!

Matt
  • 935
  • 6
  • 16
0

The best advice was from: xtofl.myopenid.com ^^^^

If you don't understand the purposes of patterns, your really not going to use objects to their fullest. You need to know why inheritence, polymorphism, interfaces, factories, decorators, etc. really make design easier by addressing particular issues.

DreamWerx
  • 2,888
  • 1
  • 18
  • 13
0

Instead of learning OO from scratch, I think it'd be easier if you took on a framework that facilitates object-oriented programming. It will "force" you to use the right OOP methods; you will be able to learn from the way the framework is written as to how to do OOP best.

I'd recommend the QCodo PHP5 framework http://www.qcodo.com. It has great video tutorials on how to set it up, as well as video trainings (http://www.qcodo.com/demos/).

Full disclosure: I've been developing on top of this framework for two years, and I've contributed code to their codebase (so I'm not completely impartial :-)).

Alex Weinstein
  • 9,823
  • 9
  • 42
  • 59
0

Another pointer for learning OO:

Most OO tutorials will focus on inheritance (e.g. class X extends class Y). I think this is a bad idea. Inheritance is useful, but it can also cause problems. More importantly, inheritance isn't the point of OO. The point is abstraction; hiding the implementation details so you can work with a simple interface. Learn how to write good abstractions of your data, and you'll be in good shape. Don't sweat the inheritance stuff right away.

JW.
  • 50,691
  • 36
  • 115
  • 143
0

I have been in your shoes, but I saw the light after I read this book (a few times!) http://www.apress.com/book/view/9781590599099 After I read this, I really "got" it and I haven't looked back. You'll get it on Amazon.

I hope you persist, get it, and love it. When it comes together, it will make you smile.

Composition beats inheritence.

  • 1
    "Composition beats inheritance" :O Oh no you didn't! – Christian Mann Nov 09 '10 at 03:28
  • **2021-08-30 11:18:50** link result -- Sorry, the page you requested is unavailable. The link you requested might be broken, or no longer exists. dmid://uu966brokenlink1630347 – dreftymac Aug 30 '21 at 18:19