gpt4 book ai didi

php 命名空间,访问全局类

转载 作者:行者123 更新时间:2023-12-04 16:52:48 24 4
gpt4 key购买 nike

从 php 文档中,我们访问全局类,如

<?php
namespace A\B\C;
class Exception extends \Exception {}
$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception
$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>

然而,当医生说的时候,我迷路了
<?php
$a = new \stdClass;
?>

在功能上等同于:
<?php
$a = new stdClass;
?>

这里 http://php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.shouldicare

有人可以解释一下文档在这里说的是什么。

谢谢。

最佳答案

就在这两个代码示例的正上方 in the docs是重要的标题:

If I don't use namespaces, should I care about any of this?

No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:



所以这里的意思不是你可以写 new stdClass;在命名空间内并使其等效,但是如果您根本不使用命名空间,那么您不必担心反斜杠 new \stdClass;
在命名空间中工作时,规则确实适用,您将需要使用 new \stdClass; .

这不仅适用于通用 stdClass ,但对任何类。
// Without namespaces:
$mysqli = new MySQLi(...);

// With namespaces
$mysqli = new \MySQLi(...);

关于php 命名空间,访问全局类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com