frozenway
V2EX  ›  PHP

如何实例化一个有命名空间的动态类?如下代码:

  •  
  •   frozenway · Jan 11, 2021 · 3070 views
    This topic created in 2125 days ago, the information mentioned may be changed or developed.
    namespace app\index\model;
    
    function custom($bcids, $param){
        foreach($bcids as $custom){
            $file = env('extend_path').'custom/'.$custom['module'].'.php';
            if(file_exists($file)){
                $res = \custom\$custom['module']::instance()->run();
            }
        }
    }
    

    类文件在 custom 目录下,现在这样会报错,如果变量换成这样

    $res = \custom\Hello::instance()->run();
    

    则不会报错,大神,求助该怎么写?

    8 replies  •  2021-01-11 18:49:27 +08:00
    frozenway
    frozenway
    OP
    Jan 11, 2021
    1
    是 TP5.1 的
    Fishdrowned
    Fishdrowned
    Jan 11, 2021❤️1
    2
    $res = "\\custom\\{$custom['module']}"::instance()->run();
    ben1024
    ben1024
    Jan 11, 2021❤️1
    3
    1.字符拼接 "{$xxx}"
    2.exec 执行脚本
    jswh
    jswh
    Jan 11, 2021❤️1
    4
    动态访问时基于字符串的,你可以简单的理解为编译器会先把字符替换到代码里,再执行代码,
    \custom\$custom['module'],这里的问题时不符合语法规范,namespace 不能后街变量。
    所以你得先搞出个完整的带 namespace 的类的字符串,然后再去调用。结果就是 2 楼。
    jswh
    jswh
    Jan 11, 2021❤️1
    5
    @jswh
    动态访问是基于字符串的,你可以简单的理解为编译器会先把字符替换到代码里,再执行代码,
    \custom\$custom['module'],这里的问题是不符合语法规范,namespace 不能后接变量。
    所以你得先搞出个完整的带 namespace 的类名的字符串,然后再去调用。结果就是 2 楼。

    -------
    着急下班,一堆错字
    rophie123
    rophie123
    Jan 11, 2021 via iPhone
    6
    PHP 牛逼
    wjfz
    wjfz
    Jan 11, 2021❤️1
    7
    2 楼正解。
    我之前是这么弄的。

    $channelClass = "\\common\\services\\sms\\" . ucfirst($channel);
    if (!class_exists($channelClass)) {
    throw new NotFoundExceptions("短信发送类{$channelClass}不存在");
    }
    justseemore
    justseemore
    Jan 11, 2021❤️1
    8
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1806 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 00:17 · PVG 08:17 · LAX 16:17 · JFK 19:17
    ♥ Do have faith in what you're doing.