简体   繁体   English

转到PHP5 SPL

[英]Moving to PHP5 SPL

After not really working with PhP for a long time, I am moving into php 5 territory. 在没有真正与PhP合作很长一段时间后,我正在进入php 5领域。 One of the things I am now trying to figure out, is how to use spl autoload functionality. 我现在要弄清楚的一件事是如何使用spl autoload功能。 And before I make stupid beginners errors, could you please confirm / advice: 在我犯愚蠢的初学者错误之前,请你确认/建议:

As far as I understand, the SPL_autoload does not mean there is no need for includes anymore; 据我了解,SPL_autoload并不意味着不再需要包括在内; I will still need to include the configuration I want to use manually like this: 我仍然需要包含我想要手动使用的配置,如下所示:

require_once("includess/php_ini_settings.php"); require_once( “includess / php_ini_settings.php”);

In the php_ini_settings.php I subsequently can run an autoloader, to load all the php files in a certain directory, such as my classes directory: 在php_ini_settings.php中,我随后可以运行自动加载器,将所有php文件加载到某个目录中,例如我的classes目录:

// Directory for classes
define('CLASS_DIR', 'classes/');

// Add classes dir to include path
set_include_path(CLASS_DIR);

spl_autoload_extensions(".php"); // comma-separated list
spl_autoload_register();

Is this indeed the right (and most efficient) way to autoload classes into all my pages? 这确实是将所有类自动加载到我的所有页面中的正确(且最有效)的方法吗?

-- added: -- It is mentioned that unless you use a different naming scheme, the is no need to specify an autoloader. - 添加: - 提到除非您使用不同的命名方案,否则无需指定自动加载器。 I assume the naming scheme default is using the class name as filename, in non-caps? 我假设命名方案默认使用类名作为文件名,在非大写字母?

You don't really need the spl_autoload_extensions() and spl_autoload_register() part, unless you use a different naming scheme. 除非使用不同的命名方案,否则您实际上不需要spl_autoload_extensions()spl_autoload_register()部分。 So you basically just need to add your class path to the include path, like you already do. 所以你基本上只需要将类路径添加到包含路径,就像你已经做的那样。

I suggest using SPL_autoload_suxx() from http://bugs.php.net/49625 as your __autoload() function though to have more sensible case-sensitivity: 我建议使用来自http://bugs.php.net/49625的 SPL_autoload_suxx()作为你的__autoload()函数,尽管它具有更合理的区分大小写:

function __autoload($cn) {
    $rc = false;
    $exts = explode(',', spl_autoload_extensions());
    $sep = (substr(PHP_OS, 0, 3) == 'Win') ? ';' : ':';
    $paths = explode($sep, ini_get('include_path'));
    foreach ($paths as $path) {
        foreach ($exts as $ext) {
            $file = $path.DIRECTORY_SEPARATOR.$cn.$ext;
            if (is_readable($file)) {
                require_once $file;
                $rc = $file;
                break;
            }
        }
    }
    return $rc;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM