- Suppose there are namespaces A and A\B respectively.
In the scope of A, can I refer a class named C within A\B just C without prepending B\?
- Why there are no prepending global indicator \ in namespaces? eg ) namespace \A;
In the scope of A, can I refer a class named C within A\B just C without prepending B\?
Suppose there are namespaces A and A\B respectively.
No there is A and B is inside it.
In the scope of A, can I refer a class named C within A\B just C without prepending B\?
Yes if you are in A\B you can use C
<?php
namespace A\B;
class C {}
Is accessible in code which is like:
<?php
namespace A;
$C = new B\C;
Or
<?php
namespace A\B;
$C = new C;
But you cant jump to C without letting the autoloader know about B as it will look for a class in A called C, but C is in B.
<?php
namespace A;
$C = new C;
Why there are no prepending global indicator \ in namespaces? eg ) namespace \A;
There is, you cant do:
<?php
namespace A\B;
$C = new \A\B\C;
// but not
$C = new A\B\C;
If you want a global namespace you cant do:
<?php
namespace;
Or
<?php
namespace \;
But you can do:
<?php
namespace {
class A {}
}
Which is like no namespace at all.
What is the relationship between the scope created by function and by namespace?
Function scope does not have anything to do with namespaces.
But a function declared in a namespace, is in a namespace and only accessible through its namespace.
<?php
namespace A;
function B() {
echo 'Value B';
}
echo B();
// or
echo \A\B();
// this wont work
echo \B();