【发布时间】:2018-06-15 06:14:03
【问题描述】:
我一直在学习我最新的 Wordpress 插件的命名空间和自动加载。
我在确定是否也可以使用自动加载器来静态实例化类时遇到问题。
到目前为止我做了什么
我已将此自动加载器添加到我的插件文件中:
spl_autoload_register( 'bnfoAutoload' );
function bnfoAutoload( $class ) {
// project-specific namespace prefix
$prefix = 'BnfoAutoload\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/';
// does the class use the namespace prefix?
$len = strlen( $prefix );
if ( strncmp( $prefix, $class, $len ) !== 0 ) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr( $class, $len );
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace( '\\', '/', $relative_class ) . '.php';
// if the file exists, require it
if ( file_exists( $file ) ) {
require $file;
}
}
我已经让自动加载功能有效地为类的新实例化实例例如:
$response = new BnfoAutoload\Includes\Tester();
$exact_response = $response->testFunction();
并通过在调用 静态方法时读取this SO post,例如
BnfoAutoload\Includes\Tester::testStaticFunction()
上下文
但是,有时我想静态实例化一个类,例如,如果我想添加一个过滤器。
例如这将是“classfile.php”;
namespace BnfoAutoload\Includes\
class LoadClass {
public function __construct() {
add_action( 'wp_head', [ $this, 'loadFunction' ];
}
public function loadFunction() {
// something
}
}
new LoadClass();
可能的解决方案
选项 1: 我可以在我的插件文件中手动要求 classfile.php,然后静态实例化该类。
require_once ('classfile.php' );
选项 2: 我可以在插件文件中实例化这些静态类,此时它们会被自动加载器拾取
new BnfoAutoload\Includes\LoadClass();
我不确定其中任何一个是否正确,因此非常感谢任何替代想法。
【问题讨论】:
-
有什么东西阻止你使用 composer?
-
可能没有,但我之前没有使用过composer,我还没准备好开始。
-
好吧,那就用
spl_autoload_register吧。 -
@chay22。我目前正在使用 spl_autoload_register。我已经更新了我的例子来展示它。我遇到的问题不是自动加载,而是自动加载静态实例化的类。谢谢
标签: php wordpress namespaces autoload