PHP命名空间和"use"

132

我对命名空间和use语句有点困惑。

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

我试图使用相对路径来实现,所以我在所有类中都加入了以下内容:

namespace Shape; 

在我的圆形类中,我有以下内容:

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

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

class Circle extends Shape implements ShapeInterface{ ....
如果我使用include语句,就不会出现错误。但如果我尝试使用use语句,就会出现以下错误:

致命错误:类'Shape\Shape'未在 /Users/shawn/Documents/work/sites/workspace/shape/Circle.php的第8行找到

请问是否有人能够为我提供一点指导?

关于这个话题,也可以参考:https://dev59.com/xJDea4cB1Zd3GeqPb3QH - Peter
2个回答

190
use operator 是用来给类、接口或其他命名空间的名称提供别名的。大多数 use 语句是用来引用你想要缩短的命名空间或类的:
use My\Full\Namespace;

等同于:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

如果使用use操作符与类名或接口名一起使用,它具有以下用途:
// 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操作符与自动加载不要混淆。通过注册自动加载器(例如使用spl_autoload_register),可以自动加载类(无需使用include)。您可能想阅读PSR-4以了解适合的自动加载器实现。

如果我创建另一个名为bootstrap.php的文件,并在其中放置一个自动加载器以及$circle = new Circle();,它会包含Circle.php,但是我会收到一个错误:致命错误:类'Shape'未找到.../Circle.php第6行。它似乎加载了Circle.php但没有加载Shape.php。Circle被定义为:class Circle extends Shape implements ShapeInterface。 - Shawn Northrop
如果我从上述类中删除命名空间,自动加载程序就可以正常工作。但是当形状类的接口中有命名空间时,我会遇到上述错误。 - Shawn Northrop
1
创建了一个 gist 以提供示例。不幸的是,gist 无法有子文件夹。将 bootstrap.php 放在一个文件夹中,并将其他类放在名为 'Shape' 的子文件夹中。 - cmbuckley

16
如果您需要将您的代码分组到命名空间中,请使用关键词 namespace:

file1.php


namespace foo\bar;

在file2.php文件中

$obj = new \foo\bar\myObj();

你也可以使用use。如果在file2中您输入:

use foo\bar as mypath;

则您需要在文件的任何地方使用mypath而不是bar

$obj  = new mypath\myObj();

使用 use foo\bar;use foo\bar as bar; 等效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接