Classes and OOP in PHP

This tutorial describes an introduction to classes and object oriented programming in PHP.
Provided by Olate / www.olate.com

Object oriented programming (OOP) is a commonly used term when discussing modern programming techniques. One of the things that makes humans stand out is the ability to categorize - we put objects into categories of similar type of function. For example, we have the category vehicle. Within this category, you have the different types of vehicle - car, bug, train, van. In the same bag, a llama is a type of animal. This analogy applies to programming - we create functions to do specific tasks and then group similar functions into classes. No only does this organize everything, but also allows a common access point for these similar functions.

OOP is a relatively new type of programming as far as PHP is concerned. PHP4 does not provide the full facilities a fully object oriented language such as a C++ provides as standard; but PHP5 improves upon this with much more OOP support. This allows updates to be made to the class functions without affecting the main code - you don't necessarily need to know how a class/function does it's job, just how to use that function.

Classes can't do anything on their own. They must contain class functions, sometimes called methods. You define these functions just as if you were creating any normal function, however, you need to do it within the class structure.

Lets first create a class called Cow. This class will then contain the functions of the Cow. The first thing you do is to define the class:

Sample 1. Defining the class.
<?php
class Cow
{

}
?>

As with functions, you encase the functions within the curly braces { and }. There is no semicolon ; anywhere as yet. Also notice that you do not have any parameters, it is class Cow not class Cow($variable). You do not pass anything to the class itself, you pass it to the functions within the class.

Next, we'll create our first function (method) - this is defined exactly the same as if you were not using classes:

Sample 2. Defining the class with some method.
<?php
// first we define the class
class Cow
{
    
// define the function moo() - no parameters     
    
function moo()
    {
        
// define the variable
        
$sound 'Moooooo!';
        return 
$sound;
    }
}
?>

Now, if we want to use the moo() function of the Cow class, we first need to create a new object. When you use functions from a class, you must create an object; hence the name object oriented programming. This is very simple. You create the new class object 'in' a variable. So here we go:

Sample 3. Creating new class object.
<?php
// create new Cow object
$daisy = new Cow();
?>

This simply creates the object from the Cow class within the variable $daisy. So if you want to access any of the Cow class functions, you reference them through $daisy. Once we have done this, we can then call the moo() function as so:

Sample 4. Calling the class method.
<?php
echo $daisy->moo();
?>

This will result in Moooooo being echoed to the page. You will notice the -> which effectively says echo the result of the moo() function in the object called $daisy. This is exactly the same as if you had just defined the function normally outside a class and done:

Sample 5. Calling the function.
<?php
echo moo();
?>

If you put this code together then, you will get something like this:

Sample 6. Creating the class.
<?php
// first we define the class
class Cow

    
// define the function moo() - no parameters
    
function moo()
    {
        
// define the variable
        
$sound "Moooooo";
        return 
$sound;        
    }
}

// create new Cow object
$daisy = new Cow();
echo 
$daisy->moo();
?>

So what is the point in that? You could have just created a function moo() and not have to mess around with classes. Yes, true, but what happens when you have more functions? A Cow doesn't just moo:

Sample 7. Full code of the class.
<?php
// first we define the class
class Cow
{
    private 
$eaten;

    
// define the function moo() - no parameters     
    
function moo()
    {
        
// define the variable
        
$sound "Moooooo";
        return 
$sound."<br>";
    }

    function 
eat_grass($colour)
    {
        if(
$colour == "green"){
            
// cow is happy
            
$this->eaten true;
            return 
$this->moo();
        }
    }

    function 
make_milk()
    {
        if(
$this->eaten){
            return 
"Milk produced<br>";
        }else{
            return 
"Cow has not eaten yet<br>";
        }
    }
}
?>

This class is slightly more complicated. It now contains three functions as well as a class variable. After we have declared the class, you will see this:

private $eaten;

You will remember from functions that if you assign a value to a variable within a class, that value is lost once you return from the class. However, we have declared the variable $eaten as a class variable. This is done using the private at the beginning and allows any of the class functions to access and assign values to it. You can see this in action in the eat_grass() function:

$this->eaten = true;

This is setting the $eaten function as true. The fact that it is a class variable is shown by the $this-> at the beginning. As with when we were echoing the result of moo() earlier, this basically means assign true to the class variable eaten.

In the same function, we are using $this->moo(). This is accessing the class function moo() from within another function and returning the result.

Finally, we will call these functions and try out the new class we just wrote:

Sample 8. Code usage.
<?php
// create the Cow object daisy
$daisy = new Cow();
echo 
$daisy->moo();
echo 
$daisy->make_milk(); /* Cow has not eaten yet */
$daisy->eat_grass("green");
echo 
$daisy->make_milk(); /* Milk produced */
?>

You obviously need to include the class definition in the same file as you call the functions so the final version of the file will look something like:

Sample 9. Full example.
<?php
// first we define the class 
class Cow

    private 
$eaten
                
    
// define the function moo() - no parameters 
    
function moo(){
        
// define the variable 
        
$sound "Moooooo!<br>";
        return 
$sound
    }
    
    function 
eat_grass($colour){
        if(
$colour == "green"){
            
// cow is happy 
            
$this->eaten true
            return 
$this->moo();
        }
    }
    
    function 
make_milk(){
        if(
$this->eaten){
            return 
"Milk produced!<br>";
        }else{
            return 
"Cow has not eaten yet!<br>";
        }
    }
}

// create the Cow object daisy
$daisy = new Cow();
echo 
$daisy->moo();
echo 
$daisy->make_milk(); // cow has not eaten yet
$daisy->eat_grass("green");
echo 
$daisy->make_milk(); // milk produced

?>

The result is following:

Moooooo!
Cow has not eaten yet!
Milk produced!

And that concludes the PHP classes tutorial! Although I haven't touched on the advanced features of classes such as constructors, destructors and extending, these are more important when you are creating complex classes and for now, you'll do fine without them.

Comments


Please post only comments related to the original tutorial. Be polite and helpful, do not spam or offend others.
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory






Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.