簡體   English   中英

如果有兩個具有相同名稱的類,php類如何確定要擴展哪個類?

[英]How does a php class determine which class to extend, given there are two class with the same name?

鑒於我有兩個User類,一個位於/model/User.php中,另一個位於/assets/User.php中

現在我想要一個從/model/User.php擴展User類的類,但似乎php總是在尋找/assets/User.php中的那個。 知道php如何確定從哪個類擴展?

使用名稱空間

user.php

class User {
    function someMethod(){}
}

myUser.php

namespace My;

class User {
    function someMethod(){}
}

你可以像這樣使用它:

include 'user.php';
include 'myuser.php';

$user1 = new User();
$user2 = new \My\User();

您可以使用名稱空間: PHP Manual

您應該(如果使用)設置適當的spl_autoload_register函數( http://php.net/manual/en/function.spl-autoload-register.php ),以便能夠自動加載具有相同名稱的文件中的對象,命名對象不能相同。

您可以通過名稱和存儲文件的路徑來區分對象。

例如,您需要bootstrap.php中的核心類並定義自動加載功能:

    <?php // bootstrap.php

require_once Core.php;
spl_autoload_register(array('Core', 'auto_load'));

$myUserClass = new MyClasses_User() // the required files for the class are loaded because of auto_load, PHP determines the right classes due to naming conventions: DirName_ClassName 

?>


<?php // Core.php

define('DIR_SEPARATOR', '/');

class Core {

  // Autoloading
    public static function auto_load($class, $dir_classes = 'classes')
    {
    $file = str_replace('_', DIR_SEPARATOR, $class); // replace _ by / for path to file

        if ($path = find_file_based_on_class_name($dir_classes, $file))
        {
            // Load the class file
            require $path;
        }
    }

?>

<?php
// classes/Model/User.php
class Model_User {
 // define the class
}
?>

// classes/Assets/User.php
<?php
class Assets_User {
 // define the class
}
?>

// classes/MyClasses/User.php
<?php
class MyClasses_User exdends Model_User {
 // define the class
}
?>

暫無
暫無

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

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