php 命名空間(namespace)原理與用法實例小結(jié)
本文實例講述了php 命名空間(namespace)原理與用法。分享給大家供大家參考,具體如下:
命名空間一個最明確的目的就是解決重名問題,PHP中不允許兩個函數(shù)或者類出現(xiàn)相同的名字,否則會產(chǎn)生一個致命的錯誤。這種情況下只要避免命名重復就可以解決,最常見的一種做法是約定一個前綴,也可以采用命名空間的方式解決
TestSpace.php
<?php namespace Demo\Test; //聲明一個命名空間Demo class Test1 { static function test() { return "my class name demo1"; } function test1() { return "2222222222222222222B"; } }
模式一 直接實例該類
index1.php
require("TestSpace.php"); $ms1 = new \Demo\Test\Test1(); echo $ms1->test1() . "<br />\n"; echo \Demo\Test\Test1::test();
模式二 use 載入該類
index2.php
require("TestSpace.php"); use Demo\Test\Test1; //導入命名空間Demo\Test下的Tese1類 $ms2 = new Test1(); echo $ms2->test1() . "<br />\n"; echo Test1::test();
模式三 use載入命名空間
index3.php
use Demo\Test; //載入命名空間Demo\Test 這一層級 $ms3 = new Test\Test1(); echo $ms3 ->test1() . "<br />\n"; echo Test\Test1::test();
模式四
index4.php
use Demo\Test as test; $ms3 = new test\Test1(); echo $ms3 ->test1() . "<br />\n"; echo test\Test1::test();
至此 thinkphp 3.2版本中我們看到的
namespace Home\Controller; use Think\Controller;
namespace 聲明的是該文件的命名空間;
use 載入在Think命名空間下的Controller 類
tip : Controller 類 位于 Thinkphp/Library/Think/Controller.class.php
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關(guān)文章
PHP連接SQLServer2005的實現(xiàn)方法(附ntwdblib.dll下載)
為了php連接sql2005 ,我在網(wǎng)絡上找了一大堆資料在我的csdn博客中.晚上3:05分時候終于搞定了2012-07-07php數(shù)組函數(shù)序列之in_array() 查找數(shù)組值是否存在
in_array() 函數(shù)在數(shù)組中搜索給定的值2011-10-10