Внезапно я не могу динамически создать экземпляр класса. Я могу создать экземпляр, если я вызываю его напрямую, но вызов его с переменной не будет работать. Вот, Что не работает:PHP - не может динамически создать экземпляр класса
$database_class = 'MysqlConnection';
$class = new MysqlConnection();
$other_class = new $database_class();
Первая конкретизация, что делает $class
, работает отлично. Во-вторых, делая $other_class
, терпит неудачу и выдает следующую ошибку:
PHP Fatal error: Class 'MysqlConnection' not found in /pronounce-php/src/Database/Connect.php on line 47
Что я здесь делаю неправильно? Heres весь файл, если он помогает:
<?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;
}
}
* Первое создание экземпляра, создающего класс $, отлично работает. * - Вы уверены? –
Да, он отлично работает. Я обнаружил, что если я использую полный путь пространства имен в динамическом экземпляре, он также работает. Интересно, почему он не связывает имя namespaced и выражение «use» ... –
Документы описывают поведение так же, как вы его пережили, поэтому я предполагаю, что он просто обрабатывает PHP: [PHP динамические языковые функции] (http://php.net/manual/en/language.namespaces.dynamic.php) – enricog