7.11. Adding Properties to a Base Object

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( ).

Solution

Use the built-in base class, stdClass :

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

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 <david@example.com>

The pc_print_address( ) function takes a name and email address and converts it to a format as you might see in the ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.