PHP 命名空间和 "use"

标签 php namespaces

我在命名空间和 use 语句方面遇到了一点问题。

我有三个文件:ShapeInterface.phpShape.phpCircle.php

我正在尝试使用相对路径来执行此操作,因此我已将其放入所有类中:

namespace Shape; 

在我的圈子类(class)中,我有以下内容:

namespace Shape;
//use Shape;
//use ShapeInterface;

include 'Shape.php';
include 'ShapeInterface.php';    

class Circle extends Shape implements ShapeInterface{ ....

如果我使用 include 语句,我不会出错。如果我尝试 use 语句,我会得到:

Fatal error: Class 'Shape\Shape' not found in /Users/shawn/Documents/work/sites/workspace/shape/Circle.php on line 8

有人可以就这个问题给我一些指导吗?

最佳答案

use operator用于为类、接口(interface)或其他命名空间的名称提供别名。大多数 use 语句引用您想要缩短的命名空间或类:

use My\Full\Namespace;

相当于:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

如果 use 操作符与类或接口(interface)名称一起使用,它有以下用途:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

use 运算符不要与 autoloading 混淆。 .通过注册一个自动加载器(例如使用 spl_autoload_register)来自动加载一个类(不需要 include)。您可能想阅读 PSR-4查看合适的自动加载器实现。

关于PHP 命名空间和 "use",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10542012/

相关文章:

c++ - 扩展最初在内联命名空间的封闭命名空间中定义的内联命名空间中的命名空间

PHP HTTP 请求

php - 在偶数行中具有不均匀单元格元素的 HTML 表格 (colspan)

php - 如何在 PHP 中启用用户自定义域

mysql - 使用 PDO 的 undefined variable

c++ - 命名空间语法 "::Foo"

php - MySQL性能: DATE vs TINYINT

c++ - 全局命名空间前缀的规则和实践?

PHP Xpath 抓取可能的命名空间问题

php - 在 PHP 中使用命名空间中的静态函数作为回调