天天看點

《php面向對象》 第15課:命名空間

命名空間是在php5.3版本以加入的。

命名空間一個最明确的目的就是解決重名問題,PHP中不允許兩個函數或者類出現相同的名字,否則會産生一個緻命的錯誤。

預設情況下,所有常量、類和函數名都放在全局空間下,就和PHP支援命名空間之前一樣。

命名空間通過關鍵字namespace 來聲明。如果一個檔案中包含命名空間,它必須在其它所有代碼之前聲明命名空間。

比如,我們建立一個檔案:student.php

<?php
namespace model; //定義命名間

//類Student在model命名空間中
class Student
{
    public function say(){
        echo 'hello';
    }
}
           

我們建立一個測試檔案:test.php

<?php
use model\Student; //引入 model命名空間的Student 類

require_once 'student.php';

$stu = new Student();
$stu->say();
           
要想使用命名空間中的類,必須要引入這個類,如:use model\Student

引入命名空間的類時,也可以給類重新命名,原有的類名不能再使用。

<?php
use model\Student as Stu; //引入 model命名空間的Student 類,并重命名為Stu

require_once 'student.php';

$stu = new Stu();
$stu->say();
           

在有些場景下必須給類重新命名,比如還有一個類也是Student,在檔案student2.php中

<?php

namespace controller;

class Student
{
    public function showme()
    {
        echo '自我介紹';
    }
}
           

那麼在test.php中如何同時使用這兩個student類呢?

<?php
use model\Student as StuModel;
use controller\Student as StuController;

require_once 'student.php';
require_once 'student2.php';

$stu1 = new StuModel();
$stu1->say();

$stu2= new StuController();
$stu2->showme();
           
給引入的類重新命名,解決了難題。

在後續的課程中,我們定義的類都使用了命名空間。

繼續閱讀