PHP命名空间

命名空间

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

animals.php

<?php

namespace 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

<?php

require_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代码修改如下

<?php

function __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编程实战

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值