PHP Series – Classes and Objects

Understanding Classes and Objects, regardless of the programming language, is not one of the easier tasks.

Many authors take different approaches to explain it, but in the end all of them means the same.

First let’s define object: Object is structural / behaviorist representation of a Class.

Using the same concept but in backwards, a Class is a programable definition of a object that is usually generated by a system requirements or data models.

Just by saying what each one is doesn’t help, so to better work this out, let’s take a look on a more visual concept.

Consider that you are now developing an application that will generate and display a Crayon Box.

To correctly create this application, the first step is to analisys how the crayon box is structured, so if we list what is the crayon box structure we would have:

  • Crayon Box and it’s properties (such as: is the box made of paper ?; how many crayons inside?; etc)
  • Crayons and it’s properties (such as: what color is the crayon?; how much of it is left?; etc)

Now that the structure is defined, the next step is to generate the classes for the objects that we have just defined.

First let’s take a look on the crayon box object. As properties it carries how the box is build and how many crayons it can hold. Programming this object into a class is a simple task but you must follow some rules:

  1. A class will always start with class as definition for a class
  2. A class must have an unique name and as a variable, should never start with a number
  3. The methods and properties inside a class must be set to either public, private or protected. Where public is a method / property that can be accessed by any part of the application, private is a method / property that can be accessed solely by the object itself and protected is a method / property that can only be accessed by the object itself or it’s child’s.
  4. All methods and properties must be accessed using the $this-> operator. Exception only to abstract class that allow the access by className::methodOrProperty to be called.

These are the basics but a class also have some properties of it’s own, such as  polymorphism, abstraction and inheritance. Since all of these are conceptual, here is a brief overview:

  • Polymorphism is the characteristic of the class to allow the object to morph to some other object. In another words, polymorphism is a way to represent the same object through multiple states or stages and what that really means is a way of programming to an interface or base class without regard to an object’s concrete class.
  • Abstraction has a bunch of well defined and complex wording to explain what it is, but keeping it simple, abstraction is just a programmable way to set a generic class with generic characteristics and methods that can be correctly rewritten by the subclasses. It’s more like your boss giving you a piece of paper which says that the class Crayon Box should have the methods, construct, load, get, set and the properties howManyCrayons and boxMaterial and you, based on that, write the class.
  • Inheritance is the simplest of all. As you can imagine, inheritance is the characteristic that allow a rich uncle class to give to his favorite nephew subclass all his belongings that are not private (off course no nephew would like underwear from his rich uncle).

Let’s now program the Crayon Box class:

class crayonBox {

public $howManyCrayons;
public $boxMaterial;
public $crayons;

public function __construct()
{
// the constructor will set all that needs to be default set at the moment that
// the class is generated
$this->howManyCrayons = 12;
$this->boxMaterial = ‘cardboard’;
$this->crayons = array();
}

public function __get($variable)
{
return $this->$variable;
// if the variable passed is set, it will return it’s value
// ex.: return $this->howManyCrayons;
}

public function __set($variable, $value)
{
if ($variable !== ‘crayons’) {
$this->$variable = $value;
// just like on the get, it will set the value on the given variable
// ex.: $this->howManyCrayons = 12;
}
// for setting the crayons we will use the add method
}

public function addCrayon($crayon)
{
if (sizeof($this->crayons) < $this->howManyCrayons) {
$this->crayons[] = $crayon;
return true;
}
return false;
}

public function display()
{
$displayString =  “Box Made Of: {$this->boxMaterial} \n”;
$displayString .= “Max number of crayons:  {$this->howManyCrayons} \n”;
$displayString .= ‘Current crayons at the box:’ . “\n”;
foreach ($this->crayons as $index => $crayon) {
$displayString .= “Crayon at position #{$index}: \n”;
$displayString .= ” – Color: {$crayon->color} \n”;
$displayString .= ” – How much is left: {$crayon->howMuchIsLeft}”;
}
return $displayString;
} // display
} // public class crayonBox

At this moment the crayonBox class is sucessfully defined. We have created methods ,using the magic methods from PHP5, to set and get, have defined a constructor and have defined a method that will add crayons on the crayons box.

The application is not complete still. We still need to define the class witch will specify the crayons object.

class crayon
{
public $color;
public $howMuchIsLeft;

public function __construct()
{
$this->color = ‘white’;
$this->howMuchIsLeft = ‘100%’;
}

public function __get($variable)
{
return $this->$variable;
}

public function __set($variable, $value)
{
$this->$variable = $value;
}
} // class crayon

Now with the definitions of the objects already set, the application can be invoked and the objects constructed.

As mentioned before, let’s consider a visual approach for this and we will do this by creating a crayon box with 6 crayons.

<?php
$box = new crayonBox();
// at this moment the constructor is called and the crayon box is set with it’s default properties
$white = new crayon();
/* just like the crayon box the constructor is called and the default values are set, in this case, the white doesn’t need to have it’s values re-set since they have already been set on the construtor defaults. */
$red = new crayon();
$red->color = red;
// here the setter method is called and the red crayon is set to a red color;
$blue = new crayon();
$blue->color = blue;
$blue->howMuchIsLeft = ‘90%’;
// just to exemplify all properties, here we will also re-set the value of the how much is left from the crayon
$black = new crayon();
$black->color = ‘black’;
$yellow = new crayon();
$yellow->color = ‘yellow’;
$green = new crayon();
$green->color = ‘green’;

// now let’s add those crayons at the box
$box->add($white);
$box->add($red);
$box->add($blue);
$box->add($black);
$box->add($yellow);
$box->add($green);

// And to finish, let’s display the box information
echo $box->display();
?>

At this moment all we did was to create several objects of the crayon type and add them to another object called crayon box. Inside the crayon box class the object crayon is called and it’s properties are used to be part of the display string.

The result of the code above is:

The box is made of: cardboard
The maximum number of crayons are: 12
Current crayons at the box:
Crayon at postion 0:
– color: white
– how much is left: 100%
Crayon at postion 1:
– color: red
– how much is left: 100%
Crayon at postion 2:
– color: blue
– how much is left: 90%
Crayon at postion 3:
– color: black
– how much is left: 100%
Crayon at postion 4:
– color: yellow
– how much is left: 100%
Crayon at postion 5:
– color: green
– how much is left: 100%

These classes and objects are some simple examples of the concept OOP (oriented object programming) with PHP5. More methods and validations could be added, such as remove crayon, set the crayon in use, etc, but this would only add complexity on the script and not explain the concept behind it.

In the next step we will take a fast look on how to create a database structure for a user / login application.

Have fun, until next part of the series.

Advertisements

About mcloide

Making things simpler, just check: http://www.mcloide.com View all posts by mcloide

4 responses to “PHP Series – Classes and Objects

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: