《php物件導向》 第15課 命名空間

2021-09-26 14:27:45 字數 1393 閱讀 2158

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

命名空間乙個最明確的目的就是解決重名問題,php中不允許兩個函式或者類出現相同的名字,否則會產生乙個致命的錯誤。

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

命名空間通過關鍵字namespace 來宣告。如果乙個檔案中包含命名空間,它必須在其它所有**之前宣告命名空間。

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

<?php

namespace model; //定義命名間

//類student在model命名空間中

class student

}

我們建立乙個測試檔案: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

}

那麼在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();

給引入的類重新命名,解決了難題。

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

PHP物件導向之命名空間

namespace china function getinfo namespace usa function getinfo getinfo i am a america usa getinfo i am a america china getinfo 我是中國人 如果將相對路徑轉成絕對路徑 公共...

PHP學習 30 PHP物件導向 命名空間

namespace spacea const title 我在網上學習php function multi n,m class staff public function get name public function set name,value namespace spaceb const t...

《php物件導向》 第12課 靜態成員

在類中除了有普通的成員 普通的屬性和普通的方法 還有靜態的成員 靜態屬性和靜態方法 先看下面的 class book 第一次例項化物件 b1 new book b1 showme 第二次例項化物件 b2 new book b2 showme 第三次例項化物件 b3 new book b3 showm...