php中namespace use用法執行個體分析,namespace執行個體分析_PHP教程

來源:互聯網
上載者:User

php中namespace use用法執行個體分析,namespace執行個體分析


本文執行個體講述了php中namespace use用法。分享給大家供大家參考,具體如下:

現在說這個感覺有點過時了,但是感覺用namespace的人還是不多,估計還是因為不習慣吧。

class把一個一個function組織起來,namespace可以理解成把一個一個class,function等有序的組織起來。個人覺得,namespace的主要優勢有

第一,可以更好的管理代碼
第二,檔案一多,可以避免class,function的重名
第三,代碼可讀性增強了

1. 定義namespace

namespace userCenter;//php代碼namespace userCenter\register;//php代碼namespace userCenter\login { //php代碼}

命名空間不能嵌套或在同一代碼處聲明多次(只有最後一次會被識別)。但是,你能在同一個檔案中定義多個命名空間化的代碼,比較合適的做法是每個檔案定義一個命名空間(可以是相同命名空間)。

2. 調用namespace

\userCenter\register; //絕對調用userCenter\login; //相對調用use userCenter\register; //引用空間use userCenter\register as reg; //引用空間並加別名

3. 執行個體說明

login.class.php

<?phpnamespace userCenter;function check_username(){ echo "login OK
";}class login{ public function save(){ echo "login had saved
"; }}?>

regist.class.php

<?phpnamespace userCenter\regist{ function check_username() { echo "regist OK
"; } class regist{ public function save(){ echo "regist had saved
"; } }}?>

test.php

<?phprequire "login.class.php";require "regist.class.php";use userCenter\regist; //使用use調用空間use userCenter\regist as reg; //as定義別名echo \userCenter\check_username(); //絕對調用$login = new \userCenter\login();echo $login->save();echo regist\check_username(); //相對調用echo reg\check_username(); //別名調用$regist = new reg\regist();echo $regist->save();

使用use,比絕對調用要好一點,好比給class,function等加了一個首碼,這樣看起來就比較清楚了。

希望本文所述對大家PHP程式設計有所協助。

您可能感興趣的文章:

  • thinkphp autoload 命名空間自訂 namespace
  • PHP命名空間(namespace)的動態訪問及提示
  • PHP命名空間(namespace)的使用基礎及樣本
  • PHP命名空間(Namespace)簡明教程
  • PHP命名空間(Namespace)的使用詳解
  • thinkphp命名空間用法執行個體詳解
  • PHP中的命名空間詳細介紹
  • PHP中的命名空間相關概念淺析
  • php命名空間學習詳解
  • PHP 命名空間執行個體說明
  • PHP 5.3新特性命名空間規則解析及進階功能

http://www.bkjia.com/PHPjc/1094750.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1094750.htmlTechArticlephp中namespace use用法執行個體分析,namespace執行個體分析 本文執行個體講述了php中namespace use用法。分享給大家供大家參考,具體如下: 現在說這個感覺有...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.