Implicit Evaluation with PHP

15 August 2006

Introspection in PHP

There are two object-oriented functions which I seem to use most when doing any kind of implicit evaluation coding. They are get_object_vars doc and get_class_vars doc. Get_Object_Vars and Get_Class_Vars are very similar in what they do. Given a particular class or object, it will return an array of the variables and their values in that class or object. Therefore, given this class:

class person {
var $name;
var $age = 0;
}
$bob = new person;

get_class_vars(”person”) returns:

array ("name" => "", "age" => 0)

And get_object_vars ($bob) returns:

array ("name" => "", "age" => 0)

Though the results are the same, already, there is a subtle difference: Get_object_vars only works on an instantiated object. Get_class_vars operates on a class name represented by a string. But the results so far are the same.
Let’s suppose, though, that our $bob instantiation is expanded.

$bob->name = "jones";
$bob->address = "123 America Street";

You might notice that address is not defined in the person class (and further, person doesn’t extend anything that would define it.
get_class_vars(”person”) returns:

array ("name" => "", "age" => 0)

And get_object_vars ($bob) returns:

array ("name" => "jones", "age" => 0,
"address" => "123 America Street")

Suddenly, get_object_vars is returning additional variables besides what the class defines, while the class returns the exact same results.
PHP’s ability to add more variables introduces the ability to use real PHP as meta data. It still carries all the runtime weight of normal code, unfortunately, but there are times it can be useful. Perhaps you need to build a custom casting function.

function cast_as ($object, $destination) {
$dest = new $destination;
$props = array_keys (get_class_vars ($destination));
foreach ($props as $key => $dummy) {
if (isset ($object->$key)) {
$dest->$key = $object->$key;
} /* else doesn't need to be copied */
}
return $dest;
}

You’ll find get_object_vars used repeatedly through Fortitude ObjectDataAdapter. But basically, the best way to think of get_object_vars is a cheap and clean way to cast any object to an array.
PHP has numerous other introspection functions, though I don’t seem to use the rest nearly so often (except get_class). The meta information about a program that these functions provide is a large part of what makes implicit evaluation in PHP practical.

No Comments currently posted.

Post a comment on this entry: