Wordpress - add_menu_page,[$ this,'function']不是有效的类名或对象

时间:2013-11-22 18:39:53

标签: php wordpress oop

我想理解为什么我不能在它自己的班级中使用[$ this,'function']。

这有效:

的init.php

if ( is_admin() )
{
    require ( dirname ( __FILE__ ) . '/inc/admin/Admin.php' );
    add_action('admin_menu', ['Mango\Admin', 'adminMenu'] );
}

/inc/admin/Admin.php - 版本1(正常工作)

<?php namespace Mango;

class Admin
{
    public function adminMenu()
    {
    //this is the main item for the menu
    add_menu_page(
        'Mango Settings', //page title
        'Mango Settings', //menu title
        'manage_options', //capabilities
        'mango-settings', //menu slug
        [ 'Mango\Admin', 'settingsPage' ] // LOOK HERE *******
    );
    }

    public function settingsPage()
    {
        echo 'This is a test';
    }
}

/inc/admin/Admin.php - 版本2(无效)

<?php namespace Mango;

class Admin
{
    public function adminMenu()
    {
    //this is the main item for the menu
    add_menu_page(
        'Mango Settings', //page title
        'Mango Settings', //menu title
        'manage_options', //capabilities
        'mango-settings', //menu slug
        [ $this, 'settingsPage' ] // LOOK HERE *******
    );
    }

    public function settingsPage()
    {
        echo 'This is a test';
    }
}

错误讯息:Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /.../wp-includes/plugin.php on line 429

我真的不明白为什么我不能用add_menu_page钩子注册[ $this, 'settingsPage' ]。当然,工作版本1正在制作Mango \ Admin类的第二个副本吗?

有人可以帮我解释一下吗?

1 个答案:

答案 0 :(得分:1)

回答可能有点迟,但也可能对其他人有所帮助;

如果函数是插件中的类的成员,那么它应该是 引用为数组($ this,&#39; function_name&#39;)

http://codex.wordpress.org/Function_Reference/add_menu_page

class Admin
{
    public function adminMenu()
    {
    //this is the main item for the menu
     add_menu_page(
        'Mango Settings', //page title
        'Mango Settings', //menu title
        'manage_options', //capabilities
        'mango-settings', //menu slug
        array( $this, 'settingsPage' ) // LOOK HERE *******
    );
    }

    public function settingsPage()
    {
        echo 'This is a test';
    }
}