Dynamic PHP child class name
I've a really easy Php question.
Is the following possible:
$foo = 'bar';
Class $foo extends Object
{
...
}
I believe any OOP developer will have an idea about what I wish to accomplish. Thanks in advance for any hints.
UPDATE: Sometimes you would want to have the script's filename as its own classname (of course you'll have to prefix the classname to minimize collission). Also... without using eval(). I should have written the code开发者_StackOverflow社区 as:
$cls = 'MyCls' . basename(__FILE__);
Class $cls extends Object
{
...
}
you could do something like:
// First define the Object class
class Object
{
}
// This will be the template class
$classDef = <<<TEXT
Class __MY_CLASS_NAME__ extends Object
{
}
TEXT;
// This will generate a class based on the given template
function generateClass($name, $classDef)
{
eval(str_replace('__MY_CLASS_NAME__', $name, $classDef));
}
// Now use it altogether
generateClass('Something', $classDef);
$a = new Something;
var_dump($a);
EDIT: I agree with other people comments.. dont know what you want to do and sure is ugly, but ... there you go..
Look into class_alias. First you create a class with a fixed name which extends Object as required. Then you create the dynamic alias.
I don't know what your specific requirements are, however, I think you are going the wrong way about it. Rather than trying to create the class name based on the file name, why not use __autolod()
to load whatever the class you like and your code will know how to find it.
精彩评论