6

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();
?>
Charles
  • 50,943
  • 13
  • 104
  • 142
knittl
  • 246,190
  • 53
  • 318
  • 364

2 Answers2

8

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
johannes
  • 15,807
  • 3
  • 44
  • 57
  • It should be possible for PHP to only autoload a class if it was not found in all existing (and imported) namespaces. If I imported a namespace every class that got properly defined (included) with that namespace should be callable. – knittl Sep 19 '11 at 19:55
  • This would lead to a massive number of autoload calls at has to call the autoloader for each imported namespace for each referenced class name. Assuming an autoload function is relative expensive (looking at the filesystem) this is quite notable. – johannes Sep 19 '11 at 19:59
  • Not to mention, I might want to create class containing files _during_ script execution and then include them to use (an unlikely, and probably not very wise scenario, but nevertheless PHP can do that) – Mchl Sep 19 '11 at 20:18
  • johannes: ok, having to call `__autoload()` for each namespace is a valid argument. A shame … – knittl Sep 19 '11 at 20:24
0

As explained johannes 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();
corretge
  • 1,751
  • 11
  • 24
  • 1
    Not what I asked for. I know I can import single classes (and alias them), but that's not my problem – knittl Sep 19 '11 at 20:22
  • Oh sorry, I know that you want to use namespaces as in C# (me too!) but as explained johannes it is not possible for now... I wanted to contribute with the aliasing class tech rather sub-namespace. – corretge Sep 20 '11 at 05:26