簡體   English   中英

類使用父級和子級名稱空間自動加載

[英]Classes autoload using namespaces for parent and children

我讀了幾篇有關在php中使用名稱空間的文章,但我還沒明白。 我有3個文件:

script.php和dog.php位於同一根文件夾abstr中。 classes animals.php類位於cls文件夾中,而dog則擴展了動物。

資料來源: cls/Animals.php:

namespace cls;
abstract class Animals { .. }

Dog.php (因為它位於根文件夾中,所以沒有名稱空間):

 class Dog extends Animals {...}

script.php

function __autoload($cls){
     $file = str_replace('\\',DIRECTORY_SEPARATOR,$cls).".php";
    if(file_exists($file)){
        require_once $file;
    } else {
        throw new Exception("File not found: ".$file);
    }
}

$dog = new Dog("German Shepard");

但是我Not found exception動物類Not found exception$file只是沒有名稱空間的Animals.php ...

  1. 誰能告訴我如何獲取名稱空間並將其包含在__autoload函數的路徑中?

  2. 還是為父級和子級使用相同的名稱空間更好?

  3. 而且據我了解,正確的名稱空間=文件位置?

如果Dog不在'cls'命名空間中,則必須為Animals類編寫完整的限定名稱:

class Dog extends \cls\Animals { ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM