Pages

Categories

Getting to grips with PHP and OOP/Classes [Part 1]

PHP4 and above, although loosely typed does offer excellent support for Object Oriented Programming. PHP5 offers far more than PHP4 when it comes to OOP but if you’re completely new to OOP as a general concept it would be wise to get to grips with the basic concepts in PHP4 before reading up on the changes in PHP5, unless of course you never intend on using PHP4 or supporting it at all.

Note: Object Oriented applications written for PHP4, if written correctly will probably “just work” in PHP5 but applications written with PHP5 OOP will not run in PHP4.

To get right down to very basics we could describe a class as nothing more than a container. This container contains a number of items (values) that we refer to as “properties” and also perhaps a number of procedures (functions) that we refer to as “methods”. One of the big buzzwords you hear used alot in OOP-speak is “encapsulation“. All that word refers to is the fact that a class is a container, therefore, the items and routines inside it are kept away from items in the global scope and items in other classes. That means that you’ll get less bugs from overwriting values in the same scope and it also means that things are just generally a lot more organised.

Let’s just take a look at a basic (PHP4) class that includes some key components you’ll use throughout any work you do in OOP.

A basic class in PHP:

<?php

/*
 A basic PHP4 class example
 – d11wtq @ w3style
 */

class example
{

    var $somevalue; //We declare all properties with "class scope" here
    var $anotherValue = 42; //We can initialize properties with values too

    function example()
    {
        //This is the constructor method
        $this->someValue = ‘test’;
    }

    //This is a method
    function sayHello()
    {
        echo ‘Hello!’;
    }

}

?>

That class has three major components. It has two properties each named “someValue” and “anotherValue”, it has a constructor which I’ll talk about in a moment and it also has a method which we can run.

As you can see, to declare a class in PHP you quite simply use the “class” keyword followed by the name you wish to use. Everything to do with our class then goes inside the curly braces. To declare class properties you use the “var” keyword outside of any methods (functions), and to declare methods you quite simply use the “function” keyword.

A constructor is a special method inside a class which runs automatically when we create an object from our class. OK ok I’m more than aware of the fact I just introduced something that might not mean anything to you yet so just bear with me ;)

What we mean by “create an object” is we take an instance of our class and store it in a variable of our choice so that we can interact with it by doing things to the variable we create (an object). The process of creating an object from a class is known as “instantiation” and we acheive it through the use of the PHP keyword “new“. We’ve already established that a class contains properties and has a number of routines. Based on that premise it may now perhaps be a little clearer why we call an object an object. Everything real in the world has properties, and most physical items do something or other (have routines). Take for example a cat; it has an age, a name, a color — these are properties. It also has the ability to walk, to meeow, to jump and to purr — these things are routines (methods).

Instantiation:

$object = new example();
//We use the "->" operator to access properties and methods in a class
$object->sayHello();

Above, we asked for an instance of our class “example” to be stored inside a variable called “object”. Simple!

Inside and outside of the class you access items by the use of the object operator “->”, so to run the method sayHello() inside the object we created we run “$object->sayHello()” as you can see above. That leads us on to exactly what “$this” means. It’s actually very simple… Just like we used $object to refer to an instance of our object from outside of the class, PHP understand $this inside the class as being itself. Therefore, inside the class you can run methods contained in itself and assign values to properties through the variable $this. You can see that done in the constructor of our class here.

OK, now it’s time to talk about exactly what the constructor is and how to create one. As stated above, a constructor is a special method which runs when we instantiate our class to create an object. To declare a constructor you simply create a function with the same name as the class it resides in.

The constructor’s job is to execute any code that may be needed in order to set our object up to do something we need it to. You can pass arguments to a constructor just like you can any other method. For example:

<?php

class speak
{
    function speak($string)
    {
        echo $string;
    }
}

$spk = new speak(‘Hello World!’); //Hello World!

?>

A practical implementation of using classes could be something like a way to handle your database work. Here’s a very basic wrapper class that allows you to do things with MySQL.

<?php

/*
 An example of a basic database wrapper class in PHP4
 – d11wtq @ w3style
 */

class db
{

    //Credentials
    var $dbName, $dbServer, $dbUser, $dbPass;
    //Used internally
    var $conn, $error;

    //Declare our constructor
    function db($server, $user, $pass, $db)
    {
        //I’m defining some constants for use later
        if (!defined(‘DB_OBJECT’)) define(‘DB_OBJECT’, 1);
        if (!defined(‘DB_ASSOC’)) define(‘DB_ASSOC’, 2);
        if (!defined(‘DB_ARRAY’)) define(‘DB_ARRAY’, 3);
       
        //Set the object up by connecting to database
        $this->connect($server, $user, $pass);
        $this->selectDb($db);
    }

    //A method (connects to the database and
    // stores the connection id in the class)
    function connect($server, $user, $pass)
    {
        //Store a connection in the "conn" property
        $this->conn = @mysql_connect($server, $user, $pass);
        //If something went wrong, ask our error function
        // to store the error
        if (!$this->conn) $this->setError(mysql_error());
    }

    function selectDb($db)
    {
        //Try to use a gievn database, using our
        // stored connection ID
        if (!@mysql_select_db($db, $this->conn))
            $this->setError(mysql_error());
    }

    //Query the database on our specific connection ID
    // Then return the result
    function query($query)
    {
        $result = @mysql_query($query, $this->conn);
        if (!$result) $this->setError(mysql_error());
        return $result;
    }

    //Read data from our result
    function getData($result, $return_type=DB_OBJECT)
    {
        switch ($return_type)
        {
            case DB_ARRAY:
            $data = @mysql_fetch_array($result);
            break; //End case
            case DB_ASSOC:
            $data = @mysql_fetch_assoc($result);
            break; //End case
            case DB_OBJECT: default:
            $data = @mysql_fetch_object($result);
        }
        return $data;
    }

    //Store an error message
    function setError($err)
    {
        $this->error = ‘<br />Something went wrong. MySQL said: <strong>’.$err.‘</strong>’;
    }

    //Just fetches whatever is stored in our
    // "error" property
    function getError()
    {
        return $this->error;
    }

}

?>

The class above contains enough information to run queries against a given database, and can pull data in the form of an object or an array. That’s a very limited set of methods but you could quite easily pack it with functions to automatically collect multiple rows, seek through result sets, even set up user permissions and change the MySQL password for a user.

That’s it, that’s really all there is to it on a basic level. In Part 2 we’ll go on to look at some slightly more advanced ideas but these are still key things to know before steaming off ahead in OOP.

To finish off we’ll just take a look at that database class in use:

$db = new db(‘localhost’, ‘my_user’, ‘my_password’, ‘my_database’);

$result = $db->query("
select
    a.some_field,
    b.another_field
from
    some_table as a,
    another_table as b
where
    a.fk_id = b.pk_id
    and username=’admin’
limit 1"
);

$row = $db->getData($result);

echo $row->some_field;

Continue to Part 2 →

This entry was posted on Wednesday, April 5th, 2006 at 11:33 am and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No Responses to “Getting to grips with PHP and OOP/Classes [Part 1]”

No comments yet

Leave a Reply







XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>