Dynamically Access Subclass Properties in PHP
Monday, December 6, 2010 2:27:04 AM
The other night I was working on some template rendering code and wanted to handle classes with properties that were classes with properties
An example:
class Class1 {
public $Prop1 = "Property 1";
public $Prop2;
public function __construct()
{
$Prop2 = new Class2();
}
}
class Class2 {
public $SubProp1 = "Sub Property 1";
}
In my template I wanted to include tokens, such as {{Prop1}} and {{Prop2->SubProp1}} and then pass an instance of Class1 to the template processor, with the template and have it replace the tokens with the appropriate properties.
This is all fine and dandy for the main properties, but when you start working with the inner class properties I couldn't get it to work and could not find any shortcut methods online. Enter my new function (Part of my DAO class).
public static function GetPropertyValue($object, $dataitem)
{
if (strstr($object, "->"))
{
$parts = explode("->", $object);
$sub = $dataitem->$parts[0];
$subobj = "";
for ($i = 1; $i < count($parts); $i++)
{
if ($i > 1)
{
$subobj .= "->";
}
$subobj .= $parts[$i];
}
return DAO::GetPropertyValue($subobj, $sub);
} else {
return $dataitem->$object;
}
}
Now all I have to do is load my template, retrieve a list of tokens and for each token perform a $template = str_replace("{{" . $token . "}}", DAO::GetPropertyValue($token, $classinstance), $template);
If you know of a way to dynamically retrieve this subproperty I would love to know about it, otherwise, feel free to use this code in any of your projects (commercial or open source). If you do use it, drop me a line and let me know.