PHP 在全局命名空间中使用类

编程入门 行业动态 更新时间:2024-10-28 16:27:01
本文介绍了PHP 在全局命名空间中使用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个使用 PDO 的 DB 包装类,在构造函数中我创建了一个 PDO 对象.包装器类在我们的命名空间中,我们使用的是自动加载器.问题是在我们的命名空间中找不到 PDO 类,所以我尝试使用全局命名空间,如 此处.

I have a DB wrapper class that uses PDO and in the constructor I create a PDO object. The wrapper class is in our namespace and we are using an autoloader. The issue is that the PDO class cannot be found within our namespace, so I tried using the global namespace as described here.

//Class file namespace CompanyCommon; class DB { private function __construct(){ $this->Handle=new PDO(...); } }

有了这个,我得到了这个(正如预期的那样):

With this, I get this (as expected):

Warning: require(...vendorsCompanyCommonPDO.class.php): failed to open stream

如果我这样做:

namespace CompanyCommon; use PDO;

我明白了:

Fatal error: Class 'DB' not found in ...includesutils.php

并且 utils.php 在错误行中包含此内容,在实现命名空间之前运行良好:

And utils.php contains this on the error line, which worked fine before implementing namespaces:

DB::getInstance();

或者我试过这个:

namespace CompanyCommon; class DB { private function __construct(){ $this->Handle=new PDO(...); } }

它试图像最初那样在我们的命名空间中加载 PDO 类.

Which tried to load the PDO class within our namespace as it originally did.

我该如何解决这个问题?我想通过执行 use PDO 或 new PDO 它会加载全局 PDO 类,但它似乎不起作用?

How can I resolve this? I thought by doing use PDO or new PDO it would load the global PDO class, but it doesn't seem to be working?

推荐答案

解决了.我没有意识到命名空间别名仅适用于当前文件,而不适用于任何未来包含的文件.在 PHP 上发现这也适用于别名:

Solved it. I didn't realize that aliasing a namespace only applies to the current file, and not any future included files. Found this on PHP which also applies to aliasing:

导入规则是基于每个文件的,这意味着包含的文件不会继承父文件的导入规则.

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

更多推荐

PHP 在全局命名空间中使用类

本文发布于:2023-11-09 14:56:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   空间   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!