gpt4 book ai didi

php - 什么在 PHP 命名空间或类元素中使用

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

我多年来一直致力于为我们的内部闭源项目维护的 PHP 框架。

当我更新它并保持 PHP 7 的编码标准时,我注意到很多开发人员在代码中调用的类和命名空间中使用\。

例如

class ClassName extends ParentClass implements
\ArrayAccess,
\Countable,
\Serializable
{
// constants, properties, methods
}

或者例如在类的函数中调用类
public function featured()
{
// Check for request forgeries
\Session::checkToken() or jexit(\Text::_('JINVALID_TOKEN'));

$user = \Factory::getUser();
$ids = $this->input->get('cid', [], 'array');
$values = ['featured' => 1, 'unfeatured' => 0];
$task = $this->getTask();
$value = \ArrayHelper::getValue($values, $task, 0, 'int');
}

为什么使用\以及它的目的是什么,因为它也可以在没有\的情况下工作。

因为我在网上看不到任何信息,\在类和命名空间中的用途是什么。

最佳答案

这在这里解释:http://php.net/manual/en/language.namespaces.fallback.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
?>
$a = new Exception('hi');使用当前命名空间中的 Exception 类,即 A\B\C
$b = new \Exception('hi');使用全局类 Exception

关于php - 什么在 PHP 命名空间或类元素中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51683453/

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