How to autoload extended classes?

I plan to use the PHP autoload function to dynamically load only the class files that are needed. Now this can create a huge mess if each separate function has a separate file. So I hope and ask if there is a way for the related classes to remain in 1 class file and still be automatically loaded.

function __autoload($class_name){
    include('classes/' . $class_name . '.class.php');
}

Say there is a class name, and then another class called dogs. The dog class extends the animal class, now if I named the dog class but not the animal class, would the animal class file be downloaded?

+3
source share
4 answers

, , ?

. , , PHP , , .

re: : . - , .

, .

+6

? .

.

auto_prepend_file ( )

class Import
{
    public static $_AutoLoad = array();
    public static $_Imported = array();

    public static function Load($sName)
    {
        if(! isset(self::$_AutoLoad[$sName]))
            throw new ImportError("Cannot import module with name '$sName'.");

        if(! isset(self::$_Imported[$sName]))
        {
            self::$_Imported[$sName] = True;
            require(self::$_AutoLoad[$sName]);
        }
    }

    public static function Push($sName, $sPath)
    {
        self::$_AutoLoad[$sName] = $sPath;
    }

    public static function Auto()
    {
        function __autoload($sClass)
        {
            Import::Load($sClass);
        }
    }
}

.

//Define autoload items
Import::Push('Admin_Layout',        App::$Path . '/PHP/Admin_Layout.php');
Import::Push('Admin_Layout_Dialog', App::$Path . '/PHP/Admin_Layout.php');
Import::Push('FileClient',          App::$Path . '/PHP/FileClient.php');

, , AutoLoad,

Import::Auto()

, "":

Import::Push('MyModule',          App::$Path . '/Module/MyModule/Init.php');

:

Import::Load('MyModule');

- Import::Push , .

+9

, , / .

, PHP-. PHP , . Java, , PHP .

. "".

0

, , , :

, , , .class.php. ,

    class animals{
        static function load(){
            return true;
        }
    }


    class dogs extends animals{

    }

    class cats extends animals{

    }

... dogs, , PHP (, , , ), :

animals::load();
$fuffy = new dogs();
0

Source: https://habr.com/ru/post/1717977/


All Articles