首頁 > php教程 > PHP开发 > 主體

PHP物件導向程式設計之命名空間與自動載入類別詳解

高洛峰
發布: 2016-12-30 10:07:16
原創
1110 人瀏覽過

本文實例講述了PHP物件導向程式設計之命名空間與自動載入類別。分享給大家供大家參考,具體如下:

命名空間

避免類名重複,而產生錯誤。

<?php
require_once "useful/Outputter.php";
class Outputter {
  // output data
  private $name;
  public function setName($name) {
    $this->name = $name;
  }
  public function getName() {
    return $this->name;
  }
}
$obj = new Outputter(); // 同一命名空间下,类名不能相同,默认命名空间为空。空也是一种命名空间。
$obj -> setName("Jack");
print $obj->getName();
//namespace useful; // 更改命名空间,否则查询不到Hello类,Fatal error: Class &#39;my\Hello&#39; not found
$hello = new Hello();
?>
<?php
// useful/Outputter.php
namespace useful; // 命名空间
class Outputter {
  //
}
class Hello {
}
?>
登入後複製

   

如何呼叫命名空間中的類別

<?php
namespace com\getinstance\util;
class Debug {
  static function helloWorld() {
    print "hello from Debug\n";
  }
}
namespace main;
// com\getinstance\util\Debug::helloWorld(); // 找不到Debug类
\com\getinstance\util\Debug::helloWorld(); // 加斜杠之后,就从根部去寻找了。
// outPut:hello from Debug
?>
登入後複製

   

   

表示全域

global.php

<?php
namespace com\getinstance\util;
class Debug {
  static function helloWorld() {
    print "hello from Debug\n";
  }
}
namespace main;
use com\getinstance\util;
//Debug::helloWorld(); //Fatal error: Class &#39;main\Debug&#39; not found
util\Debug::helloWorld();
?>
登入後複製

   

輸出:

hello from comgetinstanceutil

hello from global

:

hello from Debug

全域命名空間

<?php
namespace com\getinstance\util;
class Debug {
  static function helloWorld() {
    print "hello from Debug\n";
  }
}
namespace main;
use com\getinstance\util\Debug; // 直接使用到类
Debug::helloWorld();
?>
登入後複製

   

__autoload 自動加載類

ShopProduct.php

<?php
// no namespace
class Lister {
  public static function helloWorld() {
    print "hello from global\n";
  }
}
?>
<?php
namespace com\getinstance\util;
require_once &#39;global.php&#39;;
class Lister {
  public static function helloWorld() {
    print "hello from ".__NAMESPACE__."\n"; // __NAMESPACE__当前namespace
  }
}
Lister::helloWorld(); // access local
\Lister::helloWorld(); // access global
?>
登入後複製

   

文件夾business/ShopProduct.php

<?php
namespace com\getinstance\util {
  class Debug {
    static function helloWorld() {
      print "hello from Debug\n";
    }
  }
}
namespace main {
  \com\getinstance\util\Debug::helloWorld();
}
?>
登入後複製

output:

ShopProduct constructor

business_ShopProduct constructor

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

更多PHP物件導向程式設計之命名空間與自動載入類別詳解相關文章請關注PHP中文網!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!