Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP namespaces: equivalent to C# using

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

What I'd like (but does not work):

<?php
# myclass.php
namespace Namespace;
class myclass {
}
?>

<?php
# main.php
include 'myclass.php'
use Namespace;

new myclass();
?>
like image 582
knittl Avatar asked Sep 19 '11 19:09

knittl


1 Answers

There is none. In PHP the interpreter won't know all classes which possibly might exist (especially due to the existence of __autoload) so the run-time would running into many conflicts. Having something like this:

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

There might e a Foo\Exception which should be __autoloaded -- PHP can't know.

What you can do is import a sub-namespace:

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

or with alias:

use Foo\Bar as B;
$o = new B\Baz(); // Is Foo\Bar\Baz
like image 172
johannes Avatar answered Sep 18 '22 11:09

johannes