使用composer进行包管理以后,可能会使用命名空间。但是使用命名空间以后会发现可能MySQL数据库无法连接。具体报错为

Uncaught Error: Class 'xxxxxx\mysqli' not found in

这玩意是系统类,以前使用的时候从来不需要引入。

我目前使用的解决方案(我感觉最简单粗暴的),就是在PHP里面加一行

use Mysqli;

啥事儿都就没有了。

查资料的时候还看见SO上有一位老哥的回答How to use MySQLi inside a namespace

By default, PHP will try to load classes from your current namespace. Refer to the class in the global namespace:

$db = new \mysqli(/* ... */);

This is the same thing you'd do when referring to a class in a different namespace:

$foo = new \Some\Namespace\Foo();

Note that if you left off the beginning backslash, PHP would try to load the class relative to your current namespace. The following code will look in the namespace Project\Some\Namespace for a class named Foo:

namespace Project;
$foo = new Some\Namespace\Foo();

Alternatively, you can explicitly import namespaces and save yourself ambiguity:

namespace Project;

use Mysqli;

class ProjectClass
{
    public static function ProjectClassFunction()
    {
        $db = new Mysqli(/* ... */);
    }
}
如果觉得我的文章对你有用,请随意赞赏