如何自动加载扩展类? [英] How to autoload extended classes?

查看:108
本文介绍了如何自动加载扩展类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计划使用PHP的自动加载功能来动态加载所需的类文件。现在这可能会创建一个巨大的麻烦,如果每个单一的函数有一个单独的文件,所以我希望和问是有一个方法,有相关的类保留在1类文件,仍然是自动加载

I am planning to use PHP's autoload function to dynamicly load only class files that are needed. Now this could create a huge mess if every single function has a seperate file, So I am hoping and asking is there a way to have related classes remain in 1 class file and still be auto-loaded

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

我们假设有一个类名动物,然后是另一个名为dogs的类。 Dogs类扩展动物类,现在如果我调用dogs类但是不调用动物类,动物类文件是否仍然被加载?

Let's say there is a class name animals and then another class named dogs. Dogs class extends animals class, now if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?

推荐答案


如果我调用dogs类,但
不调用animals类,
动物类文件是否仍然加载?

if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?

是的。当你加载一个扩展另一个类的类时,PHP必须加载基类,以便知道它的扩展。

Yes. When you load an class that extends another class, PHP must load the base class so it knows what it's extending.

re:每个文件存储多个类的想法:将无法使用您提供的自动加载功能。

re: the idea of storing multiple classes per file: This will not work with the autoload function you provided. One class per file is really the best practice, especially for autoloaded classes.

如果文件中有多个类,那么你真的不应该尝试自动加载任何该文件中的类。

If you have more than one class in a file, you really shouldn't attempt to autoload any classes from that file.

这篇关于如何自动加载扩展类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆