【问题标题】:Class not found, when trying to pass class name as string, namespace issue找不到类,尝试将类名作为字符串传递时,命名空间问题
【发布时间】:2016-12-27 22:26:29
【问题描述】:

这是一个方法,其中传递了一个字符串,使用该字符串创建一个实例。示例方法:

public function action($actionType)
{
    //var_dump(new $actionType);

    if (!class_exists($actionType)) {
        //throw new Exception

    }

    if (!(new $actionType) instanceof ActionInterface) {
        ////throw new Exception
    }
    $actionType = new $actionType;
    echo $actionType->doAction();
}

但是我收到了一个找不到类的错误,但是当我手动编写类名或以这种方式手动附加命名空间$actionType = __namespace__ . "\\$actionType"; 时,就会出现错误。为什么会这样?

【问题讨论】:

  • 尝试替换新的$actionType;使用新的 $actionType();
  • @stweb 没有创建不带括号的类的实例,这是不将任何参数传递给构造函数的简写?
  • 另外,我会将$actionType = new $actionType; 放在 if 语句之间以避免创建两个实例。在最后一个 if 语句中你会这样做:if (!$actionType instanceof ActionInterface) { }
  • @harry123 你在使用某种自动加载吗?
  • 将 if (!$actionType instanceof ActionInterface) 替换为 if (!($actionType instanceof ActionInterface))。关于括号,我同意@Rasmus Rosengren,你可以跳过它。

标签: php class oop namespaces


【解决方案1】:

试试这个:

public function action($actionType) {
     //var_dump(new $actionType);
     if (!class_exists($actionType)) {
       //throw new Exception
     }
     $actionType = new $actionType;
     if (!($actionType instanceof ActionInterface)) {
        ////throw new Exception
     }

     echo $actionType->doAction();
}

【讨论】:

  • 这没有任何区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 2020-02-10
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多