Advanced PHP Tutorial

An Intro to Classes And More

Classes: An Object Oriented Approach

In the course of a project, sometimes it’s handy and logical to have an item that contains certain properties and can do certain actions. In real life, this manifests itself in our everyday life by the objects we ourselves interact with.

Take a pencil for example: there are several properties that are relevant to the pencil:

  • Length of the Staff (ie 8 in)
  • Weight of the Lead (#2 Pencil)
  • How much eraser is remaining
  • Color of the lead

Continuing with the pencil example, there are also things that the pencil can do. For example, the pencil can

  • Write
  • Erase
  • Be Sharpened

To fully utilize the pencil, though, other things need to be able to act upon the object. In the pencil example, a person needs to be able to use the pencil to write something. You could write pseudocode that represents how the stuff works together:

// Person( firstname, lastname, position, age );
$kyle = new Person("Kyle", "Keiper", "Web Programmer", 20);

// Pencil( weight, length, percent_of_eraser_left );
$pencil = new Pencil(2, 8, .7);

// Give Kyle the $pencil
$kyle->GivePencil( $pencil );

// Kyle should write some text with the pencil
$kyle->WriteText( "Kyle Keiper Wrote Some Text!" );
$kyle->EraseAllText( );

// Remove the Pencil from Kyle's Properties
$kyle->BreakPencil( );

In that example, We created an object called Kyle, of type Person, an object called Pencil of type Pencil, and then gave Kyle the Pencil. That’s the premise of basic object oriented stuff. The biggest benefit of this is that the code is reusable, in a friendly fashion. We could functionally program writing the text, and it could look like this:

person_write_text( $kyle, $pencil, "My text" );

The semantic problem with this is that there is no clear owner of the actions or properties. It’s much harder to read because it’s not clear at first. What is doing the writing? What is being used to write with? The readability is one issue with face with functional programming.

Coding Style

I tend to use Underscore Notation for variables and Pascal Case for Member Methods.

Leave a Reply

Your email address will not be published. Required fields are marked *

Thanks for your thoughts!

*