PHP - 无法动态实例化类

rev*_*101 2 php symfony

突然间,我无法动态实例化一个类.如果我直接调用它,我可以实例化它,但用变量调用它将不起作用.这里有什么不起作用:

    $database_class = 'MysqlConnection';

    $class = new MysqlConnection();
    $other_class = new $database_class();
Run Code Online (Sandbox Code Playgroud)

第一个实例化,制作$class,工作正常.第二个,制作$other_class,失败并给出以下错误:

PHP致命错误:第47行的/pronounce-php/src/Database/Connect.php中找不到类'MysqlConnection'

我在这做错了什么?如果有帮助的话,继承整个文件:

<?php

namespace PronouncePHP\Database;

use Symfony\Component\Console\Output\OutputInterface;
use PronouncePHP\Database\Connection\MysqlConnection;

class Connect
{
    private $config;

    /**
     * Construct
     *
     * @return void
    */
    public function __construct()
    {
        $this->config = include('config.php');
    }

    /**
     * Get database connection
     *
     * @return Connection
    */
    public function getDatabaseConnection($output)
    {
        $database_type = $this->getDatabaseType($output);

        $database_class = $this->makeConnectionClass($database_type);

        $connection_information = $this->getConnectionInformation($database_type);

        // if (!class_exists($database_class))
        // {
        //     $output->writeln("<error>Database type not found!</error>");
        //     $output->writeln("<comment>Please ensure that the database type is specified and that it is supported</comment>");

        //     $GLOBALS['status'] = 1;

        //     exit();
        // }
        $database_class = "MysqlConnection";

        $class = new MysqlConnection();
        $other_class = new $database_class();
    }

    /**
     * Get database type specified in config file
     *
     * @return string
    */
    public function getDatabaseType($output)
    {
        $database_type = $this->config['database'];

        if (is_null($database_type))
        {
            $output->writeln("<error>No database type specified in config.php</error>");

            $GLOBALS['status'] = 1;

            return null;
        }

        return $database_type;
    }

    /**
     * Make class name for connection
     *
     * @return string $database_type
    */
    public function makeConnectionClass($database_type)
    {
        return ucfirst($database_type) . 'Connection';
    }

    /**
     * Get connection information for specified database type
     *
     * @return string $database_type
    */
    public function getConnectionInformation($database_type)
    {
        $information = $this->config['connections'][strtolower($database_type)];

        return $information;
    }
}
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 5

该类的实际名称是PronouncePHP\Database\Connection\MysqlConnection.由于您已将其别名放在文件顶部,因此您可以将其称为MysqlConnection使用文字.这是因为文字在文字范围内是固定的,名称解析是明确的.

但是,变量中的字符串可以随时随地出现,因此无法根据use语句进行实际解析.如果要将名称用作字符串变量,则需要使用完全限定名称:

$database_class = 'PronouncePHP\Database\Connection\MysqlConnection';
Run Code Online (Sandbox Code Playgroud)