douliang1900 2015-12-19 00:06
浏览 66

从命名空间中的变量获取类

I'm trying to update my project with namespaces.
Before using namespaces I could easily call a class via a variable like so:

<?php
    $className = "Item";
    $myClass = new $className();
?>

Now, when using namespaces (with use) I'd expect this to work:
(not working allways meens: 'Can't find class' or smth like this)

<?php
    namespace myProject
    use myProject\Models

    $className = "Item";
    $myClass = new $className();   // this class has the namespace myProject\Models
    // this doesn't work! (can't find class)
    $myClass = new Models\$className();
    // nope, doesn't work either
    $myClass = new myProject\Models\$className();
    // nope
?>

but calling the same class directly - without a variable - IS working

$myClass = new Item();

What I have to do, to make it work is:

<?php
    namespace myProject;
    use myProject\Models;   // unnessecary now

    $className = "\\" . __NAMESPACE__ . "\\Models\\" . "Item";
    $myClass = new $className(); 
?>

My question now is:
If I want to call a class via a variable, do I really have to include the whole namespace as a fully qualified name?

EDIT: I found myself an answer here: Dynamic namespaced class with alias
I'll keep that question anyway, because I could not find the right answer in first place.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
    • ¥15 路易威登官网 里边的参数逆向
    • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
    • ¥50 需求一个up主付费课程
    • ¥20 模型在y分布之外的数据上预测能力不好如何解决
    • ¥15 processing提取音乐节奏
    • ¥15 gg加速器加速游戏时,提示不是x86架构
    • ¥15 python按要求编写程序
    • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入