Hi,

Stas and company decided that they wanted namespaces to have two legal
syntax choices:

1) single namespace per file:

<?php
namespace foo;
...
?>

2) multiple namespaces per file:

<?php
namespace foo1 {
}
namespace foo2 {
}
?>

I've implemented these two syntax options in a patch found at
http://pear.php.net/~greg/bracketed.patch.txt based on earlier work of
Dmitry Stogov.

It turns out there are some tricky details to work out, especially with
regard to importing via use statements.  If we just allow global,
un-namespaced code, for instance, we could end up with this mess:

<?php
use blah\blah;

$f = new blah;

namespace one {
 use foo\bar as blah;
 $a = new blah;
}

// what is this?
blah::hi();
?>

Technically, you could argue that blah::hi() should resolve to
blah\blah::hi(), but it is very difficult to track and figure out what
"blah" means by eye.  Thus, in the patch I implemented, if bracketed
namespace declarations exist, global use statements are not allowed, but
must exist within namespace ns {} brackets.

This creates a problem - how do you combine namespaced and unnamespaced
code?  To solve this, I introduced the oft-suggested "namespace {}"
syntax for un-namespaced code.  Thus, the above script would become:

<?php
namespace {
 use blah\blah;
 $f = new blah;
}
namespace one {
 use foo\bar as blah;
 $a = new blah;
}
namespace {
 use blah\blah;
 blah::hi();
}
?>

Another important point is that imports specified by the "use" statement
disappear when we exit a namespace block.  This way, it is very easy to
combine un-namespaced code that uses namespaces, and namespaced code.

Also very important to note is that the "namespace {}" syntax is
optional for any code that does not import other things via the "use"
statement - its sole purpose is to provide a clear visual and logical
wrapper within which imports occur.

Thus, this is also legal:

<?php
namespace newly\coded\stuff {
 class mine { ... }
}
// old stuff here
class PEAR { ... }
?>

Lastly, if global code does make use of namespaces, but does not import
anything, it can also happily co-exist with bracketed namespace code:

<?php
namespace ns {
 class mine { ... }
}

$a = new ns\mine;
// and so on
?>

Thanks,
Greg

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to