Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Namespaces - go up a level?

Tags:

Example1:

namespace Inori\Test;

class MainTest { }

Example2:

namespace Inori\Test\SubTest;

class SubTest extends ???? { }

Question: is there a way to quickly go up a level in namespace so SubTest could extend MainTest? something like "../MainTest"? Or am I stuck with \Inori\Test\MainTest?

like image 442
Inoryy Avatar asked Aug 30 '11 15:08

Inoryy


People also ask

When were PHP namespaces added?

To address this problem, namespaces were introduced in PHP as of PHP 5.3. The best way to understand namespaces is by analogy to the directory structure concept in a filesystem.

How does namespaces work in PHP?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

What are namespaces for PHP?

A namespace is a hierarchically labeled code block holding a regular PHP code. A namespace can contain valid PHP code. Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants. Namespaces are declared using the namespace keyword.

Should I use namespace PHP?

The main objective of namespaces is to prevent name collisions, more over they are used to group classes, methods. As you mentioned there are a lot of classes within a Laravel project so namespaces would have to be used to prevent collisions which will happen in big projects.


1 Answers

Relative namespaces aren't supported. There's a request for it though: https://bugs.php.net/bug.php?id=52504

If you import your classes at the top of the file it shouldn't be that big of a deal.

namespace Inori\Test\SubTest;
use Inori\Test\MainTest;

class SubTest extends MainTest { }
like image 85
takteek Avatar answered Oct 11 '22 08:10

takteek