Dynamic Access and Using Skills of PHP Namespace of namespace
- 2021-07-13 04:36:09
- OfStack
The namespace of PHP (namespace) is the most important new feature added in PHP 5.3. This concept has been around for a long time in C #, and namespace in php is actually the same concept as c #.
1. Dynamic access to the elements of the namespace
namespace me\poet;
function test()
{
echo '1111';
}
$fun = 'test';// You can't use it like this. In the end, $fun() Cannot dynamically call to test():Fatal error: Call to undefined function test()
$fun = '\me\poet\test';// Correct
//$fun = 'me\poet\test';// Correct
$fun();
That is, the dynamic invocation must be a qualified name or a fully qualified name (concept reference: the basis for the use of the PHP namespace)
2. Magic constants and operators
namespace me\poet;
function test()
{
echo '1';
}
echo __NAMESPACE__; // Magic constant : The name of the namespace (output me\poet )
//namespace Operator: Explicitly accesses the elements in the current namespace or child namespace, equivalent to the self Operator
\me\poet\test();
namespace\test();
// The last two lines of code are equivalent.
3. Aliases, imports, and global spaces (with multiple examples)
namespace ws\weichen\www;
use ws\weichen\www as poet;// Define aliases poet
//use ws\weichen\www; // Do not add as Take the last as the alias ( www )
function demo()
{
echo '1';
}
\ws\weichen\www\demo();
poet\demo();
//www\demo(); // Do not add as Is called in the case of
The above three lines of code have one effect.
Benefits of naming according to rules (ws\ weichen\ www): If the domain name is changed, the prefix name can be changed without affecting the use of alias www in the following code.
/* Import */
include 'hello.class.php';
use \ws\weichen\www;
use \Hello;
/*--------------------------------------------------------*/
/* Support multiple use Statement */
use \nihao\shijie as hello, \ws\weichen\www;
/*--------------------------------------------------------*/
/* Global space : Backslash call */
namespace A\B\C;
// This function is A\B\C\fopen();
function fopen()
{
$f = \fopen('demo.txt');// Call global fopen Function
return $f;
}