douqian8238 2014-09-25 12:53
浏览 180
已采纳

使用变量实例化PHP类不起作用

This is working:

$x = new classname();

This is not working:

$class = "classname";
$x = new $class();

The error I get is "Class classname not found". PHP version is 5.4.22. Any ideas? As far as I have researched into this topic this is exactly what you need to do in order to instantiate a class using a variable.

My actual testcode (copy+paste), $build = 1:

//include the update file
$class="db_update_" . str_pad($build, 4, '0', STR_PAD_LEFT);
require_once(__ROOT__ . "/dbupdates/" . $class . ".php");

$x = new db_update_0001();
$xyz="db_update_0001";
$x = new $xyz();

The class definition:

namespace dbupdates;

require_once("db_update.php");

class db_update_0001 extends db_update
{
...
}

I just found out that my editor added

use dbupdates\db_update_0001;

to the file. So that explains why "new db_update_0001();" is working. What i want to achieve is that I dynamically include database updates which are stored in files like dbupdates/db_update_0001.php

Regards, Alex

  • 写回答

2条回答 默认 最新

  • dongshi8359 2014-09-25 13:14
    关注

    You have to use the full qualified class name. Which is namespace\classname. So in your case the code should be:

    $x = new db_update_0001();
    $xyz="dbupdates\db_update_0001";
    $x = new $xyz();
    

    The use statement is useless if you like to instantiate a class by using a variable as classname.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!