我在命名空间和 use
语句方面遇到了一点问题。
我有三个文件:ShapeInterface.php
、Shape.php
和 Circle.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/