lang="en-US"> PHP Tutorial: Learning OOP – Class Basics & Extending Classes –  Design1online.com, LLC

PHP Tutorial: Learning OOP – Class Basics & Extending Classes

What Is OOP?

Object Oriented Programming (OOP) is an programming style that uses classes with attributes and methods to create objects. OOP can be used anywhere, however it’s most practical when working with relational database models or on projects where major aspects of the programming can be classified as objects.

What Is An Object?

An object is defined by a class. It has attributes and methods that describes the characteristics and actions it can perform.
  • Attribute – are commonly the objects appearance, characteristics, limitations or abilities. For example size, weight, height, shape, color, speed, hunger, and health are all attributes of an animal.
  • Methods – an action the object can perform. For example eat, sleep, drink, breed, hibernate, buy something, and equip an item are all actions an object might perform.

Class Basics

A class is a good way to abstract lots of smaller details from a bigger picture. For instance, let’s take a second to think about a vending machine. There are lots of different parts that make up a vending machine, but all combined together we only think of the vending machine as one complete unit, or object. A class uses the same kind of idea, lots of smaller parts making a bigger object.

For instance a vending machine has multiple attributes like size, shape, color, make, model and manufacturer. It also has many actions  it can perform such as responding to a button press, calculating the correct change, dispensing the change, refunding money, accepting a two letter code for an item, checking to see if there are items in that entry, dispensing the item if it has one or returning an error message. We can use classes to define the properties (attributes) and actions (methods) the vending machine can perform in PHP.

Since the vending machine is a bit more complicated than I want to get in this tutorial I’m going to choose something easier to start off with.

Fruit Class

We all know there are several different types of fruit but they all have some common characteristics. For instance all fruit has a name, color, size, and varying degrees of sweetness. These are the attributes we’re going to use for our fruit class.

Now let’s think about the kind of actions you can perform with fruit.  You can wash them, eat them and shine them to name a few. We’re going to use these actions as methods in our class.

Using this really simple break down, let’s make our fruit class:

<?php
class fruit
{
 //here are the attributes of our class
 var $name;
 var $color;
 var $size;
 var $sweet;
 var $clean;
 var $washed;

function fruit($name)
{
 //this is a default constructor. It always has the same name
 //as the class. Whenever we
 //make a fruit object this function is automatically called

 $this->name = $name; //we automatically give this fruit its name
 $this->clean = False; //our fruit always needs to be washed first
 $this->washed = 0; //we haven’t washed it any times yet
}

//but we want to be able to set other things about the fruit
function setColor($color)
{
 $this->color = $color;
}

function setSize($size)
{
 $this->size = $size;
}

function setSweet($sweet)
{
 $this->sweet = $sweet;
}

//lets make a way to wash our fruit
function wash()
{
 $this->clean = True; //our fruit is clean now
 $this->washed++; //we’ve washed our fruit one more time
}

//we want to eat our fruit now
function eat()
{
  if (!$this->clean)
    echo "You should always wash your $this->color $this->name first!!!";

 if ($this->clean && $this->washed < 2)
   echo "You’re eating a dull looking piece of $this->name...";

 if ($this->clean && $this->washed >= 2)
   echo "You're eating a shiny piece of $this->color $this->name!";

 if (!$this->clean && $this->washed >= 2)
   echo "Your $this->name is shiny but you probably should wash it first.";

 if ($this->sweet)
   echo "This fruit is sweet.";
 else
   echo "This fruit is classified as a vegetable!";
}

//we can make a shine function, that washes the surface of the fruit as well
function shine()
{
 $this->washed++;
}
} //end of our class

//let's make an orange
$orange = new fruit("Orange");
$orange->setSize("small");
$orange->setColor("orange");
$orange->setSweet(True);

//now we'll make a watermelon
$fruit = new fruit("Watermelon");
$fruit->setSize("large");
$fruit->setColor("green");
$fruit->setSweet(True);

//last but not least we'll make a tomato (which is also a fruit!)
$veggie = new fruit("Tomato");
$veggie->setSize("medium");
$veggie->setColor("red");
$veggie->setSweet(False);

echo "Washing my $orange->name.";
$orange->wash();

echo "<br>Eating my $veggie->size $veggie->name.";
$veggie->eat();

echo "<br/>Washing my $orange->name again.";
$orange->wash();

echo "<br/>Shining my $fruit->size $fruit->name.";
$fruit->shine();

echo "<br/>Eating my $fruit->name.";
$fruit->eat();

echo "<br/>Eating my $orange->size $orange->name.";
$orange->eat();

//let's see what the structure of our objects looks like
//this is useful when you're trying to find or fix a problem

print_r($orange);
echo "<br/><br/>";

print_r($fruit);
echo "<br/><br/>";

print_r($veggie);
echo "<br/><br/>";

?>

Try running this script. What happens? One of the neatest things about a class is any method you make can be applied to any object of that class. In the example above we had three different fruit objects. Even though they were all different objects they used the same methods of the fruit class and stored their own data.

You’ll also notice we can directly access or change the attributes of the class using the -> arrow the same way we call a method.

Up for a challenge?

  1. Try adding more methods to this class.
  2. Try making $veggie = $fruit. What happens when you do $veggie->name now?
  3. Try adding a method that lets you set all attributes (color, sweet, size) at the same time.
  4. What happens if you to access a method or attribute that doesn’t exist in the class?
    1. Try writing $fruit->sell();
    2. Try echoing $fruit->weight;
  5. What happens if you pass one object as a parameter to another object’s method?
    1. Add this method:

function splice($otherfruit)
{
echo “I’m trying to splice ” . $this->name . ” with this ” . $otherfruit->name . “.”;
}

Test your new method  by adding $orange->splice($fruit); to the bottom of your file.

Extending Classes

I think of an extended class as a shortcut to programming similar objects. Other people, and your traditional programming school books, will tell you it’s a class that extends the functionality of an existing class. It may also be referred to as a sub-class or child class.

Programatically an extended class is easy to create. Take this example:

class car {
  var $make;
  var $model;
  var $shift_auto;
  var $horsepower;
  var $color;
  var $fuel;
  var $mpg;

  function drive($distance)
  {
     if ($fuel - $distance > 0)
     {
       $fuel -= $distance;
       echo "Driving $distance miles";
     }
     else
       echo "You don't have enough gas to go that far.";
  }

  function refuel($amount)
  {
    $fuel += $amount;
  }

}

Our car class gives us some information about the car and the ability to drive and refuel. Now look at this extended class:

class truck extends car { 

  var $tow_capacity;
  var $has_hitch;

  function tow_vehicle($car_object)
  {
     return "Towing a " . $car_object->make . " " . $car_object->model;
  }
}

In our extended class, we automatically have all the functions and variables from the car class, but we’ve also added the ability to tow another vehicle. Try making another extended class called sportscars. What additional variables or functions do you think you’d add?

Default & Optional Parameter Values

One of the neatest things about PHP is the ability to have an optional method parameter just like you can with regular functions. Let’s refer back to our fruit class and add this method:

function fruit($type, $color = "red", size = null)
{

   if (!$size)
   {
      switch(rand(1, 3))
      {
           case 1: $size = "small";
               break;
           case 2: $size = "medium";
               break;
           case 3: $size = "large";
               break;
       }

       echo "$size $color $type<br/>";
}

Can you figure out how this method works on your own? If not that’s okay too! All of the examples below are acceptable ways to call this method:

fruit(“cherry”) — returns {size} red cherry where size is randomly selected.

fruit (“bananna”, “yellow”) — returns {size} yellow bannana where size is randomly selected.

fruit(“plumb”, “purple”, “small”) — returns small purple plum.

This fruit class now has the ability to create an object with some of the attributes set for you. It has two optional parameters, one default parameter and one required parameter. The type of fruit is required. The color of the fruit is optional, but if you don’t specify a color it will automatically default to red. The size of the fruit is also optional, but if you don’t give it a size then the function will randomly pick one.

What makes these parameters optional? We’ve assigned them to a value right in the method’s parameter list. However this doesn’t prevent us from changing the value by passing in our own.

Conclusion

In this tutorial we covered some of the basic principles of OOP and classes. You learned that classes define the abilities of an object and have both attributes and methods. You also learned how to extend a class so it inherits the attributes and methods of another class. Finally you learned how to make your methods take optional parameters or default values.

Think you have the hang of it now? Test your skills by creating a game using a class! If you get stuck you can always read this Free OOP Hangman Game Tutorial (no database required).

Are you still a bit unsure about the whole thing? That’s okay! Now you can quickly and easily generate class files based off of a table in your database using our new PHP Class File Generator Tutorial.

You may also like...

5 Responses

  1. Thankyou so much for this start-up stuff about php Classes , i surely learned a lot out of it. Where can i get such more concepts explained so clearly like this one.

  2. Rambo Jha says:

    Great explained. For the depth coverage I have referred http://www.techflirt.com/tutorials/oop-in-php/index.html

  3. Sorry, but I think that the first one is a bad, bad example. OOP is meant to try to cover “real life” features, ie, a method is either a setter/getter to an attribute of an object or an action. A tomato doesn’t eat anything, unless it is an alien one like those in “Attack of the Killer Tomatoes!”. A “Person” object might be required to wash and/or eat it, instead. Don’t you think? 😉

    • Jade says:

      Haven’t you ever played plants versus zombies, lol? In many games you won’t find “real life” features so forgoing OOP when it’s a practical and sensible design decision doesn’t make sense to me.

Leave a Reply