PHP 命名空间和内置类的问题,如何解决?

2022-01-14 00:00:00 namespaces php

我正在用 PHP 编写一个小型库,但我遇到了一些无法读取内置类的问题.例如:

I'm writing a small library in PHP and i'm having some problems with built-in classes not being read. For example:

namespace Woody;

class Test {
  public function __construct() {
    $db = new PDO(params);
  }
}

这给了我:

PHP 致命错误:在/var/www/test.php 中找不到类WoodyPDO"

PHP Fatal error: Class 'WoodyPDO' not found in /var/www/test.php

推荐答案

这个:

namespace Woody;
use PDO;

或者:

$db = new PDO(params);

以防万一,类 PDO 不是您命名空间中的全限定名称,因此 PHP 会查找不可用的 WoodyPDO.

Point in case is, that the class PDO is not a full qualified name within your Namespace, so PHP would look for WoodyPDO which is not available.

请参阅 名称解析规则文档 详细说明如何将类名解析为完全限定名.

See Name resolution rulesDocs for a detailed description how class names are resolved to a Fully qualified name.

相关文章