loading PHP class body from external file
I want to include an external file as a class body, something like this:
//$key is alphanumeric
$className='_Module_'.$key;
if(!class_exists($className))
{
eval(' class '.$className.' extends ModuleContext');
{
...include the file here...
}
}
eval('$instance=new '.$className.'();');
This does what I want:
//$key is alphanumeric
$className='_Module_'.$key;
if(!class_exists($className))
{
//There's got to be a better way to do this
$contents=rtrim(ltrim(trim(file_get_contents($fileName.'.php',true)),'<?php'),'?>');
//All on one line to preserve line numbering for errors
eval(' class '.$className.' extends ModuleContext{ '.$contents.' }');
}
eval('$instance=new '.$className.'();');
I don't like using eval to include the whole file because it generates confusing error messages:
PHP Fatal error: Call to undefined function doFoo() in test/test.php(57) : eval()'d code on line 7
and I've read in 开发者_运维知识库other posts that eval()'d code doesn't take advantage of php accelerators. Also, it requres some trimming to remove the '<?php' and '?>' tags, since they don't work so well inside a class definition.
The included file needs to be 'user friendly' to someone who is familiar with PHP, but not object oriented programming - it will have a few pre-defined functions to be filled in by the module implementer.
Is there a way to do this that doesn't use eval for the include?
If I understand you correctly, ideally you would extend your class rather than trying to evaluate ad-hoc a body for your class:
class ClassA {
public function greet( $msg ) {
echo $msg;
}
}
class ClassB extends ClassA {
public function wave( $times ) {
echo sprintf("Waves %s times!", $times);
}
}
$instance = new ClassB();
$instance->greet("Hello World");
$instance->wave("five");
Note here how I'm able to build off of my class, adding new functionality and properties to the 'body' of it.
May by problem in non using short opening tag?
精彩评论