Today's Posts Follow Us On Twitter! TFL Members on Twitter  
Forum search: Advanced Search  
Navigation
Marketplace
  Members Login:
Lost password?
  Forum Statistics:
Forum Members: 24,254
Total Threads: 80,792
Total Posts: 566,471
There are 1858 users currently browsing (tf).
 
  Our Partners:
 
  TalkFreelance     Business and Website Management     Articles From The Experts :

PHP and OOP

Thread title: PHP and OOP
Closed Thread    
    Thread tools Search this thread Display Modes  
08-25-2007, 12:12 AM
#1
Village Genius is offline Village Genius
Village Genius's Avatar
Status: Geek
Join date: Apr 2006
Location: Denver, CO
Expertise: Software
Software: Chrome, Notepad++
 
Posts: 6,894
iTrader: 18 / 100%
 

Village Genius will become famous soon enough

  Old  PHP and OOP

This is a tutorial covers the major concepts of OOP in PHP5 with usable examples that actually do something (however useless the something may be). The tutorial at this time is incomplete, only covering a few fundamental subjects, all subjects are complete in and of themselves. I will consistently add pieces when I have the time to.


What is OOP?
Object Oriented Programming, referred to as OOP is a way to efficiently reuse data in an easy to read way. It is not necessarily the best way in sheer lines of code or processing time, it also does not belong in small scripts. It makes the script easier 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 within will not work with any PHP version below 5, I recommend you use the latest stable version of PHP available. So if you haven't upgraded since the stone age, I recommend you do it soon. Virtually all shared hosts come with PHP5 unless you specifically requested otherwise, if you are on a PHP4 server, you can almost always request a transfer.

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 Code:
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
PHP Code:
<?
//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 an incredibly 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 Code:
<?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
PHP Code:
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:
To avoid the confusion that got me for a while, the -> is not a bitwise shift, it is the equivalent of a period. This may sound stupid but it had me confused for ages.



PHP Code:
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.

PHP Code:
public $id;
public 
$username;
public 
$password;
public 
$rank
This declared the variable and its scope. We will get to scopes later, but for now just use public and know it works.

Wait, 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, right? 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 , don't do that and you will get an error.

PHP Code:
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.

Now for the $this-> statement, $this-> simply means it is the variable in the instance that is being run. I will explain instances in the next section.

Implementation of Classes

Now that you know how to declare and put variables in a class, how do you 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.

PHP Code:
$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.

PHP Code:
<?
class calc
{
    public 
number;
    
    function 
add()
    {
        
$this->number++;
    }
    
    function 
subtract()
    {
        
$this->number--;
    }
}

//declare the instances
$example = new calc;
$other = new calc;
We have now created a class and two instances, they both have the number variable and the function to substract them.

PHP Code:
$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.

PHP Code:
$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.

PHP Code:
function __construct()
{
    
$this->id $_COOKIE[“id”];
    
$this->pass $_COOKIE[“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.

PHP Code:
function __construct($id,$pass)
{
    
$this->id $id;
    
$this->pass $pass;    

To implement it, use this code
PHP 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

PHP Code:
<?
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.

PHP 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.


PHP Code:
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
PHP Code:
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:
PHP Code:
<?
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:
PHP Code:
<?
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
I must admit, I rarely use inheritance. 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.


I intend on making additions whenever I have time to write them. If you find any typos or mistakes please do alert me to them and I will revise them as soon as possible.

Revision notes:
Revision 1:
-Added inheritance
-Cleaned the code by using public instead of var for class definitions. Var and public serve the same purpose, but var is not proper php5, it is only supported for php4 compatibility. Description after code has been altered accordingly.
-Made the tutorial more visually appealing.
-Posted from a topic in the PHP forum to Articles From the Experts

08-25-2007, 12:17 AM
#2
creativejen is offline creativejen
Status: Paladin
Join date: Jul 2006
Location: Sheffield, UK
Expertise: design, front-end markup
Software: Photoshop
 
Posts: 2,353
iTrader: 25 / 96%
 

creativejen is an unknown quantity at this point

Send a message via MSN to creativejen

  Old

An extension from the help in the other thread, beautiful!

Not read it yet, but i'm going to do so tomorrow night. Bookmarked!

08-25-2007, 09:32 AM
#3
Haris is offline Haris
Status: Request a custom title
Join date: Dec 2005
Location:
Expertise:
Software:
 
Posts: 2,741
iTrader: 9 / 100%
 

Haris is on a distinguished road

  Old

Printing it. Going to give it a better read.

08-25-2007, 12:54 PM
#4
Sam Granger is offline Sam Granger
Status: Request a custom title
Join date: Feb 2005
Location: The Netherlands
Expertise:
Software:
 
Posts: 2,616
iTrader: 19 / 88%
 

Sam Granger is on a distinguished road

Send a message via MSN to Sam Granger

  Old

Nice post village idiot!

Closed Thread    


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

  Posting Rules  
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump:
 
  Contains New Posts Forum Contains New Posts   Contains No New Posts Forum Contains No New Posts   A Closed Forum Forum is Closed