PHP namespaces and "use"

namespaces, php

Solution

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 My\Full\Namespace;

is equivalent to:

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

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

// 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;

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.

Problem

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 'Shape\Shape' 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?

Original source

Related problems