Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO PHP explanation For a braindead n00b

Tags:

oop

php

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?

like image 449
hellweaver666 Avatar asked Sep 17 '08 14:09

hellweaver666


1 Answers

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.

like image 184
Aquarion Avatar answered Nov 09 '22 07:11

Aquarion