Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

PHP namespaces and "use"

I am having a little trouble with namespaces and the use statements.

I have three files: ShapeInterface.php, Shape.php and Circle.php.

I am trying to do this using relative paths so I have put this in all of the classes:

namespace Shape; 

In my circle class I have the following:

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

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

class Circle extends Shape implements ShapeInterface{ ....

If I use the include statements I get no errors. If I try the use statements I get:

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

Could someone please give me a little guidance on the issue?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use MyFullNamespace;

is equivalent to:

use MyFullNamespace as Namespace;
// NamespaceFoo is now shorthand for MyFullNamespaceFoo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a MyFullClassname
use MyFullClassname as DifferentName;

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

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...