stdClass in PHP – using an object rather than an associative array

An object of type stdClass can be used in PHP 5 as an alternative to an associative array. An associative array has a number of named properties that can be set and read and so does an object. To start you off, simply cast an associative array into an object:

$info = array("question" => "Life", "answer" => 42);
$ic = (object) $info;
print $ic->answer . "\n";
print $ic->question . "\n";

which gives me:


If you want to see what that looks like inside:

$cando = get_object_vars($ic);

which gives me:

array(2) {
string(4) “Life”

But one of the great beauties of stdClass is that you can extend it and add character and behaviour; here’s a class to which values can be assigned as well as directly written in (and – remember your OO training – you shouldn’t be accessing variables directly in user code!):

class thing extends stdClass {
public function assign($key, $value = false) {
$this->$key = $value;
public function getpairs() {
$wehave = get_object_vars($this);
return $wehave;

And let’s now make some used of that:

$story = new thing();
$story->author = "Douglas Adams";

print $story->by . “\n”;
print $story->author . “\n”;
print “—–\n”;

$about = $story->getpairs();
foreach (array_keys($about) as $k) {
print (“$k – $about[$k]\n”);

And here’s the resultant output:

Douglas Adams
by – Hitchhiker
author – Douglas Adams


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s