doubu5035 2011-06-24 04:29 采纳率: 100%
浏览 25
已采纳

从外部文件加载PHP类主体

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?

  • 写回答

2条回答 默认 最新

  • dongxiezhuo8852 2011-06-24 04:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真