note 27621 added to ref.classobj
| From: | alex at rack1 dot php dot net | Date: | Fri, 13 Dec 2002 07:39:18 +0000 |
| Subject: | note 27621 added to ref.classobj | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-40848@lists.php.net to get a copy of this message | ||
Using the good old eval() function, it is possible to dynamically create classes. I found this very
useful because I could generate a class dynamically based on the structure of an XML document. For
example:
$classString = 'class someClass { var $someVar = "someValue"; }';
eval($classString);
$someObject = new someClass;
echo $someObject->someVar;
This will print "someValue" as expected. This very simple example is pointless, as it
would be easier to just create the class in the normal way, but here is where it gets interesting:
$varString = "";
for ($i = 1; $i <= 3; $i++) {
$varString .= "var \$var$i = $i; ";
}
$classString = "class someClass { $varString }";
eval($classString);
$someObject = new someClass;
echo $someObject->var1;
echo $someObject->var2;
echo $someObject->var3;
This prints 1 2 3. Cool huh?
Now it just so happens that its possible to declare classes within functions, so its actually
possible to make a function that will create a class on the parameters you supply to it. Now try
doing THAT in ASP!!!
--
http://www.php.net/manual/en/ref.classobj.php
http://master.php.net/manage/user-notes.php?action=edit+27621
http://master.php.net/manage/user-notes.php?action=delete+27621
http://master.php.net/manage/user-notes.php?action=reject+27621