2012-09-27 103 views
7

比方說,我已經聲明這樣一個命名空間:爲什麼在使用命名空間時必須包含PHP文件?

<?php 
// File kitchen.php 
namespace Kitchen; 
?> 

爲什麼我仍然必須包括在我想用kitchen.php
不PHP知道,廚房裏的所有其他文件的文件.php駐留在Kitchen命名空間中?

感謝您的回答。

+9

命名空間!=自動加載。 – Mahn

+1

因此命名空間就像虛擬目錄,自動加載用於從目錄實際加載文件?你可以使用autoload命名空間嗎?謝謝!! – intelis

+1

請點擊這裏:http://php.net/manual/en/language.namespaces.rationale.php和這裏:http://php.net/manual/en/language.oop5.autoload.php;閱讀文檔可以走很長的路:) – Mahn

回答

11

命名空間使您可以非常輕鬆地爲項目中的任何類創建自動加載器,因爲您可以在調用中直接包含類的路徑。

僞代碼名稱空間示例。

<?php 
// Simple auto loader translate \rooms\classname() to ./rooms/classname.php 
spl_autoload_register(function($class) { 
    $class = str_replace('\\', '/', $class); 
    require_once('./' . $class . '.php'); 
}); 

// An example class that will load a new room class 
class rooms { 
    function report() 
    { 
     echo '<pre>' . print_r($this, true) . '</pre>'; 
    } 

    function add_room($type) 
    { 
     $class = "\\rooms\\" . $type; 
     $this->{$type} = new $class(); 
    } 
} 

$rooms = new rooms(); 
//Add some rooms/classes 
$rooms->add_room('bedroom'); 
$rooms->add_room('bathroom'); 
$rooms->add_room('kitchen'); 

然後你./rooms/文件夾中你有3個文件: bedroom.php bathroom.php kitchen.php

<?php 
namespace rooms; 

class kitchen { 
    function __construct() 
    { 
     $this->type = 'Kitchen'; 
    } 
    //Do something 
} 
?> 

然後報告被加載哪些類

<?php 
$rooms->report(); 
/* 
rooms Object 
(
    [bedroom] => rooms\bedroom Object 
     (
      [type] => Bedroom 
     ) 

    [bathroom] => rooms\bathroom Object 
     (
      [type] => Bathroom 
     ) 

    [kitchen] => rooms\kitchen Object 
     (
      [type] => Kitchen 
     ) 

) 
*/ 
?> 

希望它可以幫助班

+3

我想他是問爲什麼懶加載默認不內置。 – Pacerier

相關問題