start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

7.12. Adding Properties to a Base Object

7.12.1. Problem

You want to create an object and add properties to it, but you don't want to formally define it as a specific class. This is useful when you have a function that requires an object with certain properties, such as what's returned from mysql_fetch_object( ) or imap_header( ).

7.12.2. Solution

Use the built-in base class, stdClass:

$pickle = new stdClass;
$pickle->type = 'fullsour';

7.12.3. Discussion

Just as array( ) returns an empty array, creating an object of the type stdClass provides you with an object without properties or methods.

Like objects belonging to other classes, you can create new object properties, assign them values, and check those properties:

$guss = new stdClass;

$guss->location = 'Essex';
print "$guss->location\n";
$guss->location = 'Orchard';
print "$guss->location\n";
Essex
Orchard

Methods, however, can't be defined after an object is instantiated.

It is useful to create objects of stdClass when you have a function that takes a generic object, such as one returned from a database fetching function, but you don't want to actually make a database request. For example:

function pc_format_address($obj) {
    return "$obj->name <$obj->email>";
}

$sql = "SELECT name, email FROM users WHERE id=$id";
$dbh = mysql_query($sql);
$obj = mysql_fetch_object($dbh);
print pc_format_address($obj);
David Sklar <[email protected]>

The pc_print_address( ) function takes a name and email address and converts it to a format as you might see in the To and From fields in an email program. Here's how to call this function without calling mysql_fetch_object( ):

$obj = new stdClass;
$obj->name = 'Adam Trachtenberg';
$obj->email = '[email protected]';
print pc_format_address($obj);
Adam Trachtenberg <[email protected]>


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.