Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP use namespace - A solution to including all classes under a namespace

Is there a solution to having to include all classes individually under a namespace?

My Laravel files are getting huge because I have to keep including a heck load of namespaces... It's pretty awful!

As a temporary solution, why might the following not be working:

namespace.Blah.txt:

use Blah\Blah; 
use Blah\Bloh;

php code:

eval( file_get_contents( "namespace.Blah.txt" );

If I could get this to work, I could evaluate the contents of a file... I do understand it's a bit noob... but... dammit!

like image 653
Jimmyt1988 Avatar asked Apr 29 '15 13:04

Jimmyt1988


People also ask

What is the use of namespace in PHP?

A namespace is used to avoid conflicting definitions and introduce more flexibility and organization in the code base. Just like directories, namespace can contain a hierarchy know as subnamespaces. PHP uses the backslash as its namespace separator.

What is the best approach for working with classes and namespace in PHP?

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. The directory which is used to group related files serves the purpose of a namespace.

Can I use two namespace in PHP?

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

Does PHP have namespace?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.


1 Answers

There isn't, but in PHP 7 you'll be able to

use FooLibrary\Bar\Baz\{ ClassA, ClassB, ClassC, ClassD as Fizbo };

As the following RFC has passed:

https://wiki.php.net/rfc/group_use_declarations

EDIT:

Note that too many uses in a class may be a sign of "smell". Isn't that particular class doing too much? Shouldn't you be creating new "base" classes and extending them?

like image 180
Antonio Carlos Ribeiro Avatar answered Oct 13 '22 00:10

Antonio Carlos Ribeiro