【问题标题】:Class error being thrown in PHPPHP中抛出类错误
【发布时间】:2014-05-29 06:57:34
【问题描述】:

我不知道为什么这段代码会抛出错误,请帮忙?

foreach ($config['commands'] as $commandName => $args) {
    $reflector = new ReflectionClass($commandName);

    $command = $reflector->newInstanceArgs($args);

    $bot->addCommand($command);
}

错误:

致命错误:未捕获的异常“ReflectionException”,带有消息“类命令\解决没有构造函数,因此您不能传递任何构造函数参数”

【问题讨论】:

  • 你没有在类中构造,所以不需要在类的对象创建时传递参数 try $reflector = new ReflectionClass();
  • 我认为这行不通,但让我试试吧。
  • 这样做给了 ReflectionClass::newInstanceArgs():内部错误:无法检索反射对象
  • 那是因为一些$commandName指向了不存在的类。

标签: php reflection


【解决方案1】:

我认为错误信息非常清楚。 The documentation 也说的基本一样:

如果类没有构造函数并且args 参数包含一个或多个参数,则[抛出]ReflectionException

您正在尝试实例化的类没有构造函数,但您正在尝试实例化它,就好像它有一个并传递参数一样。 $args 不应该被传递,或者它应该是一个空数组。您需要使 $args 适合构造函数,目前它们不匹配。

namespace Command;

class Resolve {

    // Look ma, NO CONSTRUCTOR!

}

$reflector = new \ReflectionClass('Command\Resolve');
$command = $reflector->newInstanceArgs(['foo', 'bar', 'baz']);
// doesn't match the non-existent constructor ^^^^^^^^

【讨论】:

  • 我可以在我的家庭服务器上运行相同的脚本而没有错误......它只是在我的网络服务器上......有什么理由吗?我正在使用这个脚本顺便说一句:wildphp.com
  • 我不知道。向我们展示您的课程的定义以及$args 中的内容。
  • 命名空间命令;类 Resolve 扩展 \Library\IRC\Command\Base{ protected $help = '!resolve ';受保护的 $numberOfArguments = 1;公共函数 command(){ $user = $this->arguments[0]; $user = preg_replace('@[^0-9a-z\.\-\:_\,]+@i', '', $user); $apiUri = 'website.com/'.$user.''; $getJson = $this->fetch($apiUri); $this->say(''.$user.' | '.$getJson.'');}}
  • 就是它调用的Resolve.php,希望你能把代码粘贴到cmets中... -__
  • 对 wildphp.com 的反应:我认为在 PHP5.3 中传递一个空数组会引发异常。此行为已在更高版本中更改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
相关资源
最近更新 更多