Wordpress/PHP - 命名空间/自动加载器 - 致命错误:未捕获的类型错误:call_user_func_array():参数 #1 ($function) 必须是有效的回调

问题描述

我正在完全从头开始创建我的第一个插件。每当我尝试将命名空间添加到“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"}
    }
}

解决方法

问题在于 register_activation_hook()

您的回调是 activate() 类的 TemplatePluginActivate 方法。一旦引入命名空间,就需要更新。类将是 Inc\TemplatePluginActivate

register_activation_hook( __FILE__,array( 'Inc\TemplatePluginActivate','activate' ) );

此外,您的停用操作也在激活时运行。您需要的钩子是 register_deactivation_hook()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...