Re: namespaces docs
| From: | Greg Beaver | Date: | Fri, 14 Nov 2008 20:23:15 +0000 |
| Subject: | Re: namespaces docs | ||
| References: | 1 2 3 4 5 | Groups: | php.doc |
| Request: | Send a blank email to phpdoc+get-969379691@lists.php.net to get a copy of this message | ||
Stanislav Malyshev wrote:
> Hi!
>
>> Shows that a namespace name with \ acts very differently from a
>> namespace name without \ in imports, so I don't think it is entirely
>> accurate to say that PHP namespaces don't support sub-namespacing.
>
> I'm afraid I don't understand what do you mean by "sub-namespacing"
> besides the trivial fact that if you add foo, \ and bar you get foo\bar.
> Could you please explain?
I'll try :). Aside from the import example, let's look at this code:
<?php
namespace foo;
$a = bar\buh;
?>
instantiates a class in the foo\bar namespace named buh. In other
words, it instantiates class buh from the sub-namespace bar of namespace
foo.
This is the same as C++ nested namespaces (see the example at
http://www.java2s.com/Tutorial/Cpp/0020__Language-Basics/Anestednamespace.htm)
specifically:
<quote>
// use MyNamespace1
using namespace MyNamespace1;
cout << i * MyNamespace2::j;
</quote>
which accesses:
<quote>
namespace MyNamespace1 {
int i;
namespace MyNamespace2 { // a nested namespace
int j;
}
}
</quote>
we can do something this exact thing in PHP as:
<?php
namespace MyNamespace1 {
const i = 1;
}
namespace MyNamespace1\MyNamespace2 {
const j = 2;
}
namespace MyNamespace1 {
echo i * MyNamespace2\j;
}
?>
The important line is "MyNamespace2\j" which resolves the same way as in
the C++ example.
The same principle exists in C# (from
http://msdn.microsoft.com/en-us/library/z2kcy19k(VS.80).aspx):
<quote>
using System;
namespace SomeNameSpace
{
public class MyClass
{
static void Main()
{
Nested.NestedNameSpaceClass.SayHello();
}
}
// a nested namespace
namespace Nested
{
public class NestedNameSpaceClass
{
public static void SayHello()
{
Console.WriteLine("Hello");
}
}
}
}
</quote>
which we can do in PHP as:
<?php
namespace SomeNameSpace {
class MyClass
{
static function Main()
{
Nested\NestedNameSpaceClass::sayHello();
}
}
}
namespace SomeNameSpace\Nested {
class NestedNameSpaceClass
{
static function SayHello()
{
echo "Hello";
}
}
}
?>
>> actually, "use \Long\Classname;" is a parse error - did we intend to
>> allow it?
>
> I thought it was allowed, to be compatible with use \Classname. Wouldn't
> hurt to do it, I think.
This is trivial, and can be added after the bracketed namespace support
is in 5.3 (don't forget to review the patch I sent,
http://pear.php.net/~greg/bracketed.patch.txt)
Thanks,
Greg