php 命名空間(namespace)原理與用法實(shí)例小結(jié)
本文實(shí)例講述了php 命名空間(namespace)原理與用法。分享給大家供大家參考,具體如下:
命名空間一個(gè)最明確的目的就是解決重名問題,PHP中不允許兩個(gè)函數(shù)或者類出現(xiàn)相同的名字,否則會(huì)產(chǎn)生一個(gè)致命的錯(cuò)誤。這種情況下只要避免命名重復(fù)就可以解決,最常見的一種做法是約定一個(gè)前綴,也可以采用命名空間的方式解決
TestSpace.php
<?php namespace Demo\Test; //聲明一個(gè)命名空間Demo class Test1 { static function test() { return "my class name demo1"; } function test1() { return "2222222222222222222B"; } }
模式一 直接實(shí)例該類
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; //導(dǎo)入命名空間Demo\Test下的Tese1類 $ms2 = new Test1(); echo $ms2->test1() . "<br />\n"; echo Test1::test();
模式三 use載入命名空間
index3.php
use Demo\Test; //載入命名空間Demo\Test 這一層級(jí) $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(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
整理的一些實(shí)用WordPress后臺(tái)MySQL操作命令
WordPress將其所有信息片段(包括文章、頁面、評(píng)論、博客鏈接、插件設(shè)置等)存儲(chǔ)在MySQL數(shù)據(jù)庫中。 雖然WordPress用戶可以通過網(wǎng)站后臺(tái)編輯控制以上信息片段2013-01-01PHP連接SQLServer2005的實(shí)現(xiàn)方法(附ntwdblib.dll下載)
為了php連接sql2005 ,我在網(wǎng)絡(luò)上找了一大堆資料在我的csdn博客中.晚上3:05分時(shí)候終于搞定了2012-07-07php數(shù)組函數(shù)序列之in_array() 查找數(shù)組值是否存在
in_array() 函數(shù)在數(shù)組中搜索給定的值2011-10-10