Sha*_*rop 107 php namespaces
我在命名空间和use语句方面遇到了一些麻烦.
我有三个文件:ShapeInterface.php,Shape.php和Circle.php.
我试图使用相对路径这样做,所以我把它放在所有类中:
namespace Shape;
Run Code Online (Sandbox Code Playgroud)
在我的圈子课程中,我有以下内容:
namespace Shape;
//use Shape;
//use ShapeInterface;
include 'Shape.php';
include 'ShapeInterface.php';
class Circle extends Shape implements ShapeInterface{ ....
Run Code Online (Sandbox Code Playgroud)
如果我使用include语句,我没有错误.如果我尝试use我得到的陈述:
致命错误:第8行的/Users/shawn/Documents/work/sites/workspace/shape/Circle.php中找不到类'Shape\Shape'
有人可以就这个问题给我一些指导吗?
cmb*_*ley 158
该use运营商是给别名类,接口或其他命名空间的名称.大多数use语句引用了您想要缩短的命名空间或类:
use My\Full\Namespace;
Run Code Online (Sandbox Code Playgroud)
相当于:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo
Run Code Online (Sandbox Code Playgroud)
如果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;
Run Code Online (Sandbox Code Playgroud)
该use运营商不与混淆自动加载.include通过注册自动加载器(例如)来自动加载类(无需加载spl_autoload_register).您可能希望阅读PSR-4以查看合适的自动加载器实现.
Cha*_*lie 10
如果您需要将代码订购到命名空间,只需使用关键字namespace:
file1.php
namespace foo\bar;
Run Code Online (Sandbox Code Playgroud)
在file2.php中
$obj = new \foo\bar\myObj();
Run Code Online (Sandbox Code Playgroud)
你也可以使用use.如果你在文件2中
use foo\bar as mypath;
您需要使用mypath而不是bar文件中的任何位置:
$obj = new mypath\myObj();
Run Code Online (Sandbox Code Playgroud)
使用use foo\bar;等于use foo\bar as bar;.