【问题标题】:What is right way to create new class dynamically?动态创建新类的正确方法是什么?
【发布时间】:2016-02-07 19:39:18
【问题描述】:

我有下一个目录树:

交通
--Transport.php
--Curl.php

SDK.php

SDK.php 是命名空间 MySDK 和类 SDK,在该类中我有方法:

protected function _getTransport()
{
    if (!($this->_transport instanceof Transport\Transport)) {
        $className = 'Transport\\' . ucfirst($this->getOption('transport'));
        $this->_transport = new $className();
    }
    return $this->_transport;
}

但我收到错误消息:致命错误:在 /path/to/repo/lib/SDK.php 中找不到类 'Transport\Curl' 当我将$this->_transport = new $className(); 更改为$this->_transport = new Transport\Curl(); 时,我会得到Transport\Curl 的实例。

请帮帮我,我哪里做错了?

【问题讨论】:

  • 你的类自动加载器在哪里?
  • 听起来像是命名空间问题。您使用的是作曲家和 PSR-0 还是 PSR-4 ?

标签: php


【解决方案1】:

您应该以\PHP namespace with Dynamic class name 的前缀命名空间开始

$className = '\\Transport\\' . ucfirst($this->getOption('transport'));

【讨论】:

  • 正确。但不清楚 OP 是使用\\MySDK'\\Transport\\' . ucfirst($this->getOption('transport')); 还是'\\Transport\\' . ucfirst($this->getOption('transport'));
  • 当我写 __NAMESPACE__ . '\\Transport\\' . ucfirst($this->getOption('transport')) 时,它变成了工作。
猜你喜欢
  • 2012-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多