首页 > 代码库 > php namespace use 研究

php namespace use 研究

1.file1.php:

<?php
    namespace foos;
    class demo{
        function testfn(){
            echo "sdlkfjskdjf";
        }
    }
?>

2.main.php:

<?php
    include ‘./file1.php‘;
    $getcls=new foos\demo;
    $getcls->testfn(); //这里可以正常打印出来正常执行,说明namespace是一个顶层的层次命名
?>

或者你也可以这样写:

<?php
    include ‘./file1.php‘;
    use foos/demo; //使用这个namespace
    $getcls=new demo;
    $getcls->testfn();
?>

使用namespace use的调用需要引入其他文件才可以调用其他文件的东西,才可以use其他文件的东西,否则无效。

以前没有namespace的时候直接引入文件然后直接调用,现在php有了namespace的主要目的是更好的区别模块,避免重命名冲突的现象,而不是为了实现模块的调用,调用还是include或require这些,namespace 和use主要还是为了建立命名上的层次关系,避免命名空间上的冲突。

use 某个namesp 和 直接 \namespace\cls 是一样的功能,所以我们可以看出namespace主要是为了区别层次关系,更好的定义文件的空间命名避免不必要的命名冲突。

php namespace use 研究