Php: Getting Started With Object Oriented Programming in Php5

by admin Date: 12-08-2013 php php5 oop object oriented programming


This is a tutorial covers some main concepts of OOP in PHP5 with usable examples (however useless the something may be). The tutorial only covering a few fundamental subjects, all subjects are complete in and of themselves.

What is OOP?
Object Oriented Programming, referred to as OOP is a way to efficiently reuse data in an easy to read way. It makes the script easier to be scalable, to read, maintain and expand, its simple functions are just a fancy, easier naming scheme, but its advanced features give you incredible power.

PHP4 vs. PHP5
This tutorial and the examples will not work with any PHP version below 5, use the latest stable version of PHP available. Virtually all shared hosts come with PHP5 unless you specifically requested.

PHP4 has rather limited OOP features, limited to the point where I do not use OOP in any PHP4 code. PHP5 offers OOP capabilities comparable to computer programming languages such as C++, with these full features OOP becomes a key component in large scripts. Full OOP support was by far the largest and most needed upgrade between versions. Summed up, use PHP5.

OOP Basics
This will be a long section, one of the reasons OOP is so hard is because there is so much to grasp where it wont make sense till you know it all. I will do my best to explain things in a logical manor, if things do not make sense please bear with me.

The most common implementation of OOP that I use is with a user system, sometimes its the only object in the entire script because its the only piece that is being reused. Lets say you are making a user system for a client, all you need to do is authorize it to see if they are logged in and are or arent admin. There are two ways you can go about it, the first is the non OOP way (I actually use the OOP code and the non is an adaption of it).

func.php

<?php
function auth($id,$pass)
{
    $login_query = mysql_query("SELECT * FROM `users` WHERE `id` = 'id' AND `pass`     = 'pass'");
    if(mysql_num_rows($login_query)<1)
    {
        return false;
    }
    //if it is authenticated, set the other variables
    $username = mysql_result($login_query,'0',"username");
    $rank = mysql_result($login_query,'0',"rank");
    return true;
}
function admin_auth($rank)
{
    if($rank != 1)
    {
        return false;
    }
    return true;
}
?>

index.php

<?
//auth the user
$id = sql_safe($_COOKIE["id"]);
$pass = sql_safe($_COOKIE["pass"])
if(user_auth($id,$pass) == true)
{
    //user is good
}
else
{
    //user is bad
}
?>

This is a simple example, too small to call the code truly messier, but any example large enough would not fit in this tutorial. Lets see that it looks like with OOP

head.php

<?php
class user
{
    public $id;
    public $username;
    public $password;
    public $rank;
    //this function returns true if it verifies the user and false if it does not
    function auth()
    {
        $login_query = mysql_query("SELECT * FROM `users` WHERE `id` = '$this->id'                               AND `pass` = '$this->pass'");
        if(mysql_num_rows($login_query)<1)
        {
            return false;
        }
        //if it is authenticated, set the other variables
        $this->username = mysql_result($login_query,'0',"username");
        $this->rank = mysql_result($login_query,'0',"rank");
        return true;
    }
    //this must be run after auth, if it not 2 thigs will happen
    //1. The data could be forged, this function does not authenticate the data
    //2. rank will return 0 because it is not set
    function admin_auth()
    {
        if($this->rank != 1)
        {
            return false;
        }
        return true;
    }
    function __construct($id,$pass)
    {
        $this->id = $id;
        $this->pass = $pass;
    }
}
?>

index.php

<?
include "head.php";
//assign the class
$data = new input;
//assign the cookie data
$id = $data->cookie("id");
$pass = $data->cookie("pass");
$user = new user($id,$pass);
if($user->auth() == false)
{
    //user is not good
}
else
{
    //user is good
}
?>

This code is cleaner and easier to read, it also leaves easier room for expandability. However I don't expect this to make a lick of sense to you, so lets walk though it.

Note to C++ Users:
The -> is not a bitwise shift, it is the equivalent of a period. This could confuse C++ programmers..

class user
{

This is the class declaration; just like a function, you declare it with the statement, the name and the parentheses to start and end it.

public $id;
public $username;
public $password;
public $rank;

This declared the variable and its scope. We will get to scopes later, for now just use public and know it works.

PHP doesn't need creation of a variable to use it, if it finds an undefined variable it creates it so it can be used. This is not the case with classes, with classes you have to do it like in languages like C++ or Java, you have to declare every variable , if you don't do that you will get an error.

function auth()
{
    $login_query = mysql_query("SELECT * FROM `users` WHERE `id` = '$this->id'                           AND `pass` = '$this->pass'");
    if(mysql_num_rows($login_query)<1)
    {
        return false;
    }
    //if it is authenticated, set the other variables
    $this->username = mysql_result($login_query,'0',"username");
    $this->rank = mysql_result($login_query,'0',"rank");
    return true;
}

Not only can you declare variables in a class, you can declare a function, just use the same syntax of normal functions.

For the $this-> statement, $this-> simply means it is the variable in the instance that is being run.

Implementation of Classes

Now that you know how to declare and put variables in a class,you can use it. To explain instances, lets say there is a photo you want to edit, you don't make the edits to the original, you make them to the copies, or instances. Classes work sort of the same way, classes cant be directly edited, but you can make copies of them and work with those. You can make as many copies (instances) of a class as you please. So if you have a user class and two implementations (such as as a game of pong), you don't have to go through the many lines of declaring another one, you just create two instances. To make an instance of a class, you simply use this code after the declaration.

$var = new Class_name;

And boom, you have an instance (this doesn't have to make sense just yet).

Lets create at a useless script that is far too small to need OOP and doesn't really do anything but show the above lessons. This script will have a number variable and a function to add and subtract it.

<?
class calc
{
    public number;
    function add()
    {
        $this->number++;
    }
    function subtract()
    {
        $this->number--;
    }
}
//declare the instances
calc example;
calc other;
?>

We have now created a class and two instances, they both have the number variable and the function to substract them.

$example->number = 1;
$other->number = 100;
echo "Example: ".$example."<br />Other: ".$other."<br />";

Now we have just set and displayed example's and other's number variable to their respective values.

$example->add();
$other->subtract();

Each of those functions do their processes on the instances variable as defined, $this calls to the variable of that instance.

Constructors

Constructors are statements that tell the class what to do when initialized. Generally, these set variables to values automatically instead of manually and individually later on down the road, but they can be used to do anything a normal function can be.

function __construct()
{
    $this->id = $_COOKIE[&#8220;id"];
    $this->pass = $_COOKIE[&#8220;pass"];
}

Now when you make an instance of the class this function it is in, the id and pass element will be set to their respective values. You can put any php statement in the construct statement that you could put in a function, construct is literally a function that the class runs upon creation.

You can even edit other instances of other classes so long as they are created before the class you are currently making is made. I do not recommend this because it takes one of the key features away from OOP, portability, making the class reliant on another piece of code like that makes it harder to move.

Like normal functions, construct can hold parameters, meaning if you want to force setting certain variables but you know that the value may not be consistent, just use this.

function __construct($id,$pass)
{
    $this->id = $id;
    $this->pass = $pass;
}

To implement it, use this code

$user = new user($id,$pass);

This works just like a function, the parameter count in the class declaration must be the same as the construct function. To set the parameters, you just declare the class like you would call a function.

Inheritance

Inheritance is not PHP passing a variable to another application when the die() command is called. Inheritance is a method of taking variables from an already created class to another one. It is called with the extend command. When you inherit another classes properties, designated variables become part of the extending class. Lets look at what it does

<?
class first
{
    public $first_class_variable;
    public function assign_variable($x)
    {
        $this->first_class_variable = $x;
    }
}
class display extends first
{
    function show()
    {
        parent::assign_variable("Hello");
        echo $this->first_class_variable;
        return 0;
    }
}
$second = new display;
$second->show();
?>

This code will display "Hello" on the screen. Lets break down the code.

class first
{
    public $first_class_variable;
    public function assign_variable($x)
    {
        $this->first_class_variable = $x;
    }
}

The only new thing in this example is the public statement, I will get to scope operators soon.

class display extends first
{
    function show()
    {
        parent::assign_variable("Hello");
        echo $this->first_class_variable;
        return 0;
    }
}

This is full of new stuff, first is parent::assign_variable("Hello"); . The parent keyword tells php to look in the class that is being extended from, meaning that command looks for the assign_variable function in first class.

The next is echo $this->first_class_variable; . When you extend a class, all scoped variables in the parent class are brought down as if you typed them all in the current class. Therefore you refer to all inherited variables as $this->, not parent::.

Why do you need to refer to functions with parent::? $this-> finds that particular instances copy of the variable, class_name:: or parent:: (reference to the extended class) don't look for instances, it looks for the value of the member in the class itself. This only works on functions, this will not work with variables. Functions don't need to be copied for each instance because their commands are static, what you typed them to be is what they are, bar none. Variables on the other hand are dynamic and can be changed, each instance has to have a separate copy of it. Therefore when referring to a variable you use $this-> because it has been created in that instance and class::function() for functions because they remain apart from instances.

Parent simply tells PHP that the class name is whatever its parent it, you can just as well call the classes name out directly

display::assign_variable("Hello");

Will render the same result.

Scopes

Scopes tell PHP who can see that variable. There are three scopes that can be applied

Public: Anyone can access it, outside, inside and child classes.
Example: Any above code, anything can access it.

Protected: Only functions within that class and child classes can access it
example:

<?
class calc_functions
{
    protected function add($x,$y)
    {
        return $x + $y;
    }
    protected function subtract($x,$y)
    {
        return $x - $y;
    }
}
class calc extends calc_functions
{
    public function display()
    {
        echo "100 + 100 is ".parent::add(100,100)."<br />200 - 100 is ".parent::subtract(200,100);
    }
}
$math = new calc;
$math->display();
?>

As you can see, the function it extended to are able to access calc_function's functions, but if we where to make an instance of calc_function and try to call $instance->add(100,100); you would get a fatal error.

Private: Only functions within that class can access it.
Example:

<?
class calc
{
    protected function add($x,$y)
    {
        return $x + $y;
    }
    protected function subtract($x,$y)
    {
        return $x - $y;
    }
    public function display()
    {
        echo "100 + 100 is ".calc::add(100,100)."<br />200 - 100 is ".calc::subtract(200,100);
    }
}
$math = new calc;
$math->display();
?>

As you can see here, those could be accessed by the functions within the class, if we where to create a child class to inherit it, neither of those functions could be accessed by it. The same applies to outside the class.

Inheritance's Practical Uses
Inheritance's best use is for functions that will be used many times, by many different classes. Especially if they all must do the same thing and the process is open to revision. Therefore when you modify one, they all will respond to it. This enhances one of the main purposes of OOP, reusable code.

Note:
When using var to declare a variable in a class, it sets it to public, this was only continued from php4 (which didn't have scopes) for code compatibility reasons. It is deprecated and probably shouldn't be used, but it doesn't make a difference unless you need to use private or protected. Functions left without scope definition are public, I generally don't define public in my code, it doesn't make a difference.

 
by admin Date: 12-08-2013 php php5 oop object oriented programming hits : 6221  
 
 
 
 

Related Posts