【求助】使用变量作为变量名

@Ta 2019-10-23 3309点击
使用场景:

```
<?php
$class = 'abc';
require $class.'.php';
$$class = new $class;

```
想要实现引入abc.php,创建实例abc类,赋值给变量abc


@老虎会游泳
回复列表(3|隐藏机器人聊天)
  • xxb
    @Ta / 2019-10-23 / /
    <?php
    $name = 'abc';
    require "{$name}.php";
    $class = new $name();
    

    注意你的类名和文件名要一致
    CentOS 9

  • @Ta / 2019-10-24 / /
    @xxb,感谢,已经成功
    并放上最终代码,以供后人参考

    ------------
    index.php

    <?php
    $a = 't';
    require $a.'.php';
    $$a = new $a();
    print_r($t);

    ---
    t.php

    <?php
    class t
    {
        function __CONSTRUCT()
        {
            $this -> a = "test";
        }
        function test()
        {
            echo 'ok';
        }
    }
    echo "file required";

    ---
    运行结果

    file requiredt Object ( [a] => test )
  • @Ta / 2019-10-24 / /

    用自动加载不香吗?
    白日梦还是要做的, 万一实现了呢?

添加新回复
回复需要登录