Proper way to load a base class + extended class in PHP

吃可爱长大的小学妹 提交于 2020-01-06 12:13:32

问题


I am working on a personal project and it is the first time for me using OOP. My project has a base class, which is extended by others (basic setup). To clarify, this is what I am doing:

Base class:

class ABC {
  function __construct() {
    ...
  }
}

Extending class:

class DEF extends ABC {
  function __construct() {
    ...
  }
}

While the base class is always loaded, the other classes are loaded depending of the situation.

My question is, what is the proper way to dynamically load the right extended class? Should I 'import' both php? Should I cast the base class ($x = new ABC()), and then load the other class from the base class?


回答1:


You can use an autoloader at the top of your file :

function __autoload($className) {
    require_once $className . '.php';
}

Or you can use the parent class' constuctor in the child class' constuctor and import manually the php file :

require_once(your_file.php);

class DEF extends ABC {

    function __construct() {
        parent::__construct();
    }
}



回答2:


If you put all your classes in the same folder, and name them [class].php, you can put the following at the top of your script and they will all load magically

<?php
  function __autoload($class_name) {
      require_once $class_name . '.php';
  }

If they go into different folders, just implement your own scheme

Reference: http://php.net/manual/en/language.oop5.autoload.php



来源:https://stackoverflow.com/questions/17658721/proper-way-to-load-a-base-class-extended-class-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!