Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata