tags:

views:

709

answers:

10

Hi guys,

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?

+2  A: 

PHP5: http://php.net/oop5

PHP4: http://php.net/manual/en/language.oop.php

mercutio
Ignore PHP4, it's End of Life was 8/8/08. The OO differences between 4 and 5 are sufficient to mean it's a total waste looking at the php4 model
iAn
A: 

http://en.wikipedia.org/wiki/Object-oriented_programming

Dustin
Come on, give the guy a break, this is *not* what he is looking for,,,,
Lehane
+4  A: 

I recommend reading Code Complete. The few links on PHP OO are great, but this gets to the bread and butter of the idea.

Penguinix
+5  A: 

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
Good point! It's often forgotten in the rush to make every piece of code OOP-y and class-using.
phjr
+19  A: 

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

Aquarion
Any explanation that contains chunky bacon gets my vote ;)
Aeon
"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
FLYING MAGIC STUFFS ON A PLATE FOR BREAKFAST! +1
Kent Fredric
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!
phoffer
A: 

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

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

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

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

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