wiki:Php OO

Classes and Objects in PHP

Classes in php can be defined using class keyword in the same way as it is done in C++ or Java. Making the object is the same except you don't use parenthesis after the object name after the 'new' keyword (see example below).

<?php
class foo
{
    
function do_foo()
    {
        echo "Doing foo."; 
    }
}

$bar = new foo; // no parenthesis here
$bar->do_foo();
?>

The arrow in php is equivalent to the '.' operator in Java. In php, the '.' is used for string concatenation. The instance of the object is prefaced with a '$', but not the class vars or functions. Here's one with a constructor and instance vars:

<?php
class myPhpObj
{
    
    var $stuff;

    __construct()
    {
        $stuff = 'hello';
    }

    function do_foo()
    {
        echo 'Doing foo.'; 
    }
}

$myObj = new myPhpObj;
$myObj->do_foo();

echo '<br />' . $myObj->stuff;

// output:
//Doing foo.
//hello
?>

note- The '<br />' is a HTML line break, so outputting it allows what follows to show up on a new line in the browser. Looking at the source code though, it would show:

Doing foo.<br />hello

In php, you can also make objects dynamically without using classes, mostly used when the object only holds data items. One reason for doing this - there may be a function outside of your control that accepts an object as a parameter:

<?php
$myClass = new stdClass();

$myClass->name = 'A generic class';
$myClass->number = 4;

echo $myClass->name. ':' .$myClass->number;

//output:
//A generic class:4 

?>

Something we'll need to do a lot of, but could be difficult to get used to, is accessing data that is stored in arrays of objects. Perhaps the framework has built something as such:

<?php
$data = array();
$result = new stdClass();
$result->a = 1;
$result->b = 'hello';
//...

for($i=0;$i<1000000;$i++)
{
    $result = new stdClass();
    $result->a = 1;
    $result->b = 'hello';

    $data[$i] = $result;
}
?>

If you wanted to output the 4th item's 'a' value, you'd reference it as such:

    echo $data[3]->a;

The CI framework does this a lot, especially in the Database library. Query results are done this way by default, though it does provide a way to use 2D associative arrays instead.

The 'extends' keyword works as you'd expect, but instead of super() (in Java), you use 'parent::'. Namespace/scope operators also work as you'd expect, though they aren't used as much since php 5 was released. Inheritance is the basis for the CI framework.


Here is all you ever may want to know about php OO: http://www.php.net/manual/en/language.oop5.php

Last modified 7 years ago Last modified on Mar 20, 2011, 1:39:33 AM