【发布时间】:2021-07-05 21:15:59
【问题描述】:
我完全从头开始创建我的第一个插件。每当我尝试将命名空间添加到“template-plugin-activate.php”文件时,都会收到以下错误:
Plugin could not be activated because it triggered a fatal error.
Fatal error: Uncaught TypeError: call_user_func_array(): Argument #1 ($function) must be a valid callback, class "TemplatePluginActivate" not found in C:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.php:292 Stack trace: #0 C:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.php(316): WP_Hook->apply_filters('', Array) #1 C:\xampp\htdocs\wordpress\wp-includes\plugin.php(484): WP_Hook->do_action(Array) #2 C:\xampp\htdocs\wordpress\wp-admin\plugins.php(193): do_action('activate_templa...') #3 {main} thrown in C:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.php on line 292
以下是我的文件。任何帮助表示赞赏。
// inc/template-plugin.php
<?php
namespace Inc;
class TemplatePluginActivate
{
public static function activate() {
flush_rewrite_rules();
}
}
// 模板插件.php
defined( 'ABSPATH' ) or die( 'You can\t access this file.' );
if ( file_exists( dirname( __FILE__ ) . '/vendor/autoload.php' ) ) {
require_once dirname( __FILE__ ) . '/vendor/autoload.php';
}
use Inc\TemplatePluginActivate;
if ( !class_exists( 'TemplatePlugin' ) ) {
class TemplatePlugin
{
//
}
}
require_once plugin_dir_path( __FILE__ ) . 'inc/template-plugin-activate.php';
register_activation_hook( __FILE__, array( 'TemplatePluginActivate', 'activate' ) );
require_once plugin_dir_path( __FILE__ ) . 'inc/template-plugin-deactivate.php';
register_activation_hook( __FILE__, array( 'TemplatePluginDeactivate', 'deactivate' ) );
//composer.json
{
"name": "author/template-plugin",
"description": "awesome starter plugin example",
"type": "project",
"license": "GPL",
"authors": [
{
"name": "author",
"email": ""
}
],
"minimum-stability": "dev",
"require": {},
"autoload": {
"psr-4": {"Inc\\": "./inc"}
}
}
【问题讨论】:
-
请分享更多细节,比如触发该问题的代码。另外,请解释这与 Composer 有何关系
-
目标是设置我的文件,以便我以后可以使用 Composer 的自动加载。但是,在我这样做之前,我必须按照我想要的方式设置 template-plugin.php 文件。我想从 template-plugin.php 文件中删除“require_once”,而是使用“use Inc\TemplatePluginActivate;”反而。幸运的是,通过更改 register_activation_hook,我现在可以使用“namespace Inc;”来自'template-plugin-activate.php'文件。但是,我仍然无法获得“使用 Inc\TemplatePluginActivate;”去工作。我仍然遇到同样的错误。
-
好吧,我想我明白了。我必须将“模板插件激活”文件更改为大写名称,以便可以将其作为正确的命名空间读取。停用也一样。现在,“使用 Inc\Activate;”正在工作。
-
请通过编辑为您的问题添加所有说明
标签: php wordpress composer-php autoload