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条)

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭