PHP Namespaces: Equivalent to Using C #

What is the equivalent of a C # using Name.Space; to make all classes of this namespace available in the current file? Is this possible with PHP?

What I want (but not working):

 <?php # myclass.php namespace Namespace; class myclass { } ?> <?php # main.php include 'myclass.php' use Namespace; new myclass(); ?> 
+6
source share
2 answers

Not. In PHP, the interpreter will not know all the classes that may possibly exist (especially due to the existence of __autoload), so the runtime will face many conflicts. Having something like this:

 use Foo\*; // Invalid code throw new Exception(); 

There may be Foo \ Exception, which should be __autoload ed - PHP cannot know.

What you can do is import the sub-namespace:

 use Foo\Bar; $o = new Bar\Baz(); // Is Foo\Bar\Baz 

or with an alias:

 use Foo\Bar as B; $o = new B\Baz(); // Is Foo\Bar\Baz 
+8
source

As Joannes explained, or you can aliases your classes

DECLARATION:

 namespace myNamespace; class myClass { public function __toString() { return "Hello world!"; } } 

EXECUTION:

 include 'namespace.class.php'; use myNamespace\myClass as myClass; echo new myClass(); 
0
source

Source: https://habr.com/ru/post/897640/


All Articles