在PHP中自动加载类的最佳方法 [英] Best Way To Autoload Classes In PHP

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

问题描述

我正在一个项目中,我具有以下文件结构:

I'm working on a project whereby I have the following file structure:

index.php
|---lib
|--|lib|type|class_name.php
|--|lib|size|example_class.php

我想自动加载类,class_name和example_class(与PHP类相同的名称),以便在index.php中类已经被实例化,所以我可以这样做:

I'd like to auto load the classes, class_name and example_class (named the same as the PHP classes), so that in index.php the classes would already be instantiated so I could do:

$class_name->getPrivateParam('name');

我在网上看了一下,但找不到正确的答案-有人可以帮我吗?

I've had a look on the net but can't quite find the right answer - can anyone help me out?

感谢您的答复.让我扩展一下我的场景.我正在尝试编写一个WordPress插件,该插件可以放入项目中,并且可以通过将类放到插件中的功能"文件夹中来添加其他功能.永远不会有1000堂课,可能只有10堂课?

Thanks for the replies. Let me expand on my scenario. I'm trying to write a WordPress plugin that can be dropped into a project and additional functionality added by dropping a class into a folder 'functionality' for example, inside the plugin. There will never be 1000 classes, at a push maybe 10?

我可以编写一种方法来遍历'lib'文件夹的文件夹结构,包括每个类,然后将其分配给一个(类名)变量,但是我认为这不是一种非常有效的方法它,但似乎这是实现我所需要的最佳方法?

I could write a method to iterate through the folder structure of the 'lib' folder, including every class then assigning it to a variable (of the class name), but didn't think that was a very efficient way to do it but it perhaps seems that's the best way to achieve what I need?

推荐答案

请,如果您需要自动加载类,请在SPL自动加载中使用名称空间和类名约定,这将节省您的重构时间. 当然,您需要将每个类都实例化为一个对象. 谢谢.

Please, if you need to autoload classes - use the namespaces and class names conventions with SPL autoload, it will save your time for refactoring. And of course, you will need to instantiate every class as an object. Thank you.

类似于该线程: 名称空间中的PHP自动加载

但是,如果您要使用复杂的解决方法,请查看Symfony的autoload类: https://github.com/symfony/ClassLoader/blob/master/ClassLoader.php

But if you want a complex workaround, please take a look at Symfony's autoload class: https://github.com/symfony/ClassLoader/blob/master/ClassLoader.php

或者像这样(我在一个项目中做到了):

Or like this (I did it in one of my projects):

<?
spl_autoload_register(function($className)
{
    $namespace=str_replace("\\","/",__NAMESPACE__);
    $className=str_replace("\\","/",$className);
    $class=CORE_PATH."/classes/".(empty($namespace)?"":$namespace."/")."{$className}.class.php";
    include_once($class);
});
?>

然后您可以像这样实例化您的类:

and then you can instantiate your class like this:

<?
$example=new NS1\NS2\ExampleClass($exampleConstructParam);
?>

这是您的课程(位于/NS1/NS2/ExampleClass.class.php中):

and this is your class (found in /NS1/NS2/ExampleClass.class.php):

<?
namespace NS1\NS2
{
    class Symbols extends \DB\Table
    {
        public function __construct($param)
        {
            echo "hello!";
        }
    }
}
?>

这篇关于在PHP中自动加载类的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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