PHP命名空间

来源:互联网 发布:软件测试就业好不好 编辑:程序博客网 时间:2024/06/07 12:36

命名空间

命名空间是抽象的容器,创建它是为了容纳对象名称的逻辑群组。在其他语言中这是为人熟知的功能,而且有时呈现为包或者模块。脚本每天越来越大,也越来越复杂,这使得发明新的标识符难上加难。使用use语句可以讲命名空间导入局部命名空间,而且可以使用更方便的名称作为它的别名。如果文件中有多个命名空间,必须使用大括号括起来。__NAMESPACE__当前命名空间的名称。

animals.php

<?phpnamespace animals\wild{    class animal{        static function whereami(){            print "<br>".__NAMESPACE__;        }        function __construct(){            $this->type='tiger';        }        function get_type(){            return ($this->type);        }    }}namespace animals\domestic{    class   animal      {               function __construct()        {            $this->type = 'dog';        }        function get_type(){            return $this->type;        }    }}?>

index.php

<?phprequire_once('animals.php');use \animals\wild\animal as beast;$c = new beast();printf("%s\n",$c->get_type());beast::whereami();?>

显示结果

运行结果

命名空间和自动加载

__autoload函数,它用来将类自动加载到程序中,有助于自动化require_once指令

function __autoload($class){    print "$class";    exit(0);}

将index.php代码修改如下

<?phpfunction __autoload($class){    print "$class";    exit(0);}//require_once('animals.php');use \animals\wild\animal as beast;$c = new beast();printf("%s\n",$c->get_type());beast::whereami();?>

显示结果
这里写图片描述

为了借助自动加载使用命名空间,应该制定一个目录层次结构,用斜杠字符替换反斜杠,包括文件。替换字符可以通过str_replace或者preg_replace函数做到,简单的任务,使用str_replace函数比使用preg_replace更省事

【加拿大】Peter MacIntyre Brian Danchilla 【美】Miaden Gogala . PHP编程实战

0 0
原创粉丝点击