問題描述

在某種情況下,插件已將其方法封裝在類中,然後針對其中一種方法註冊了過濾器或操作,如果您不再有權訪問該類的實例,那麼您如何刪除該操作或過濾器?

例如,假設你有一個這樣做的插件:

class MyClass {
    function __construct() {
       add_action( "plugins_loaded", array( $this, 'my_action' ) );
    }

    function my_action() {
       // do stuff...
    }
}

new MyClass();

注意到我現在無法訪問該實例,如何註銷該類?這樣:remove_action( "plugins_loaded", array( MyClass, 'my_action' ) ); 似乎不是正確的方法 – 至少在我的情況下似乎不起作用。

最佳解決方案

這裏最好的辦法是使用靜態類。以下代碼應該是説明性的:

class MyClass {
    function __construct() {
        add_action( 'wp_footer', array( $this, 'my_action' ) );
    }
    function my_action() {
        print '<h1>' . __class__ . ' - ' . __function__ . '</h1>';
    }
}
new MyClass();


class MyStaticClass {
    public static function init() {
        add_action( 'wp_footer', array( __class__, 'my_action' ) );
    }
    public static function my_action() {
        print '<h1>' . __class__ . ' - ' . __function__ . '</h1>';
    }
}
MyStaticClass::init();

function my_wp_footer() {
    print '<h1>my_wp_footer()</h1>';
}
add_action( 'wp_footer', 'my_wp_footer' );

function mfields_test_remove_actions() {
    remove_action( 'wp_footer', 'my_wp_footer' );
    remove_action( 'wp_footer', array( 'MyClass', 'my_action' ), 10 );
    remove_action( 'wp_footer', array( 'MyStaticClass', 'my_action' ), 10 );
}
add_action( 'wp_head', 'mfields_test_remove_actions' );

如果您從插件運行此代碼,您應該注意到,StaticClass 的方法以及函數將從 wp_footer 中刪除。

次佳解決方案

每當一個插件創建一個 new MyClass();,它應該將它分配給唯一命名的變量。這樣,該類的實例是可訪問的。

所以如果他正在做 $myclass = new MyClass();,那麼你可以這樣做:

global $myclass;
remove_action( 'wp_footer', array( $myclass, 'my_action' ) );

這是因為插件包含在全局命名空間中,因此插件主體中的隱式變量聲明是全局變量。

如果插件沒有在某個地方保存新類的標識符,那麼在技術上這就是一個 bug 。面向對象編程的一般原則之一是某些變量在某個地方未被引用的對象可以被清理或消除。

現在,PHP 特別不像 Java 那樣做,因為 PHP 是一個 half-arsed OOP 實現。實例變量只是具有唯一對象名稱的字符串,它們是一些事物。由於可變函數名稱交互與-> 運算符的作用方式,它們只能工作。所以只是做 new class()確實可以完美地工作,只是愚蠢的。 🙂

所以,底線,從不做 new class(); 。做 $var = new class(); 並使得 $ var 可以某種方式訪問​​其他位來引用它。

編輯:幾年後

我看到很多插件的一件事是使用類似於”Singleton” 模式的東西。他們創建一個 getInstance() 方法來獲取該類的單個實例。這可能是我見過的最好的解決方案。示例插件:

class ExamplePlugin
{
    protected static $instance = NULL;

    public static function getInstance() {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }
}

getInstance() 第一次被調用,它實例化該類並保存它的指針。您可以使用它掛鈎操作。

一個問題是,如果你使用這樣的東西,你不能在構造函數中使用 getInstance() 。這是因為在設置 $ instance 之前,新調用構造函數,因此從構造函數調用 getInstance() 會導致無限循環,並且會破壞所有內容。

一個解決方法是不使用構造函數 (或至少不使用其中的 getInstance()),而是在類中顯式地設置一個”init” 函數來設置您的操作等。喜歡這個:

public static function init() {
    add_action( 'wp_footer', array( ExamplePlugin::getInstance(), 'my_action' ) );
}

有了這樣的東西,在文件的最後,在類被定義完畢之後,實例化插件就變得如此簡單:

ExamplePlugin::init();

Init 開始添加你的動作,這樣做就調用 getInstance(),它實例化類,並確保只有一個存在。如果你沒有一個 init 函數,你可以這樣來初始化類:

ExamplePlugin::getInstance();

為瞭解決原始問題,可以從外部刪除該動作鈎子 (也稱為另一個插件),如下所示:

remove_action( 'wp_footer', array( ExamplePlugin::getInstance(), 'my_action' ) );

把它放在與 plugins_loaded 動作鈎子掛鈎的東西中,它會撤消原始插件掛起的動作。

第三種解決方案

2 個小 PHP 功能,允許使用”anonymous” 類刪除過濾器/操作:https://github.com/herewithme/wp-filters-extras/

第四種方案

這是一個廣泛記錄的功能,當您無法訪問類對象時,為刪除過濾器而創建的功能 (適用於 WordPress 1.2+,包括 4.7+):

 https://gist.github.com/tripflex/c6518efc1753cf2392559866b4bd1a53

/**
 * Remove Class Filter Without Access to Class Object
 *
 * In order to use the core WordPress remove_filter() on a filter added with the callback
 * to a class, you either have to have access to that class object, or it has to be a call
 * to a static method.  This method allows you to remove filters with a callback to a class
 * you don't have access to.
 *
 * Works with WordPress 1.2+ (4.7+ support added 9-19-2016)
 * Updated 2-27-2017 to use internal WordPress removal for 4.7+ (to prevent PHP warnings output)
 *
 * @param string $tag         Filter to remove
 * @param string $class_name  Class name for the filter's callback
 * @param string $method_name Method name for the filter's callback
 * @param int    $priority    Priority of the filter (default 10)
 *
 * @return bool Whether the function is removed.
 */
function remove_class_filter( $tag, $class_name = '', $method_name = '', $priority = 10 ) {
    global $wp_filter;

    // Check that filter actually exists first
    if ( ! isset( $wp_filter[ $tag ] ) ) return FALSE;

    /**
     * If filter config is an object, means we're using WordPress 4.7+ and the config is no longer
     * a simple array, rather it is an object that implements the ArrayAccess interface.
     *
     * To be backwards compatible, we set $callbacks equal to the correct array as a reference (so $wp_filter is updated)
     *
     * @see https://make.wordpress.org/core/2016/09/08/wp_hook-next-generation-actions-and-filters/
     */
    if ( is_object( $wp_filter[ $tag ] ) && isset( $wp_filter[ $tag ]->callbacks ) ) {
        // Create $fob object from filter tag, to use below
        $fob = $wp_filter[ $tag ];
        $callbacks = &$wp_filter[ $tag ]->callbacks;
    } else {
        $callbacks = &$wp_filter[ $tag ];
    }

    // Exit if there aren't any callbacks for specified priority
    if ( ! isset( $callbacks[ $priority ] ) || empty( $callbacks[ $priority ] ) ) return FALSE;

    // Loop through each filter for the specified priority, looking for our class & method
    foreach( (array) $callbacks[ $priority ] as $filter_id => $filter ) {

        // Filter should always be an array - array( $this, 'method' ), if not goto next
        if ( ! isset( $filter[ 'function' ] ) || ! is_array( $filter[ 'function' ] ) ) continue;

        // If first value in array is not an object, it can't be a class
        if ( ! is_object( $filter[ 'function' ][ 0 ] ) ) continue;

        // Method doesn't match the one we're looking for, goto next
        if ( $filter[ 'function' ][ 1 ] !== $method_name ) continue;

        // Method matched, now let's check the Class
        if ( get_class( $filter[ 'function' ][ 0 ] ) === $class_name ) {

            // WordPress 4.7+ use core remove_filter() since we found the class object
            if( isset( $fob ) ){
                // Handles removing filter, reseting callback priority keys mid-iteration, etc.
                $fob->remove_filter( $tag, $filter['function'], $priority );

            } else {
                // Use legacy removal process (pre 4.7)
                unset( $callbacks[ $priority ][ $filter_id ] );
                // and if it was the only filter in that priority, unset that priority
                if ( empty( $callbacks[ $priority ] ) ) {
                    unset( $callbacks[ $priority ] );
                }
                // and if the only filter for that tag, set the tag to an empty array
                if ( empty( $callbacks ) ) {
                    $callbacks = array();
                }
                // Remove this filter from merged_filters, which specifies if filters have been sorted
                unset( $GLOBALS['merged_filters'][ $tag ] );
            }

            return TRUE;
        }
    }

    return FALSE;
}

/**
 * Remove Class Action Without Access to Class Object
 *
 * In order to use the core WordPress remove_action() on an action added with the callback
 * to a class, you either have to have access to that class object, or it has to be a call
 * to a static method.  This method allows you to remove actions with a callback to a class
 * you don't have access to.
 *
 * Works with WordPress 1.2+ (4.7+ support added 9-19-2016)
 *
 * @param string $tag         Action to remove
 * @param string $class_name  Class name for the action's callback
 * @param string $method_name Method name for the action's callback
 * @param int    $priority    Priority of the action (default 10)
 *
 * @return bool               Whether the function is removed.
 */
function remove_class_action( $tag, $class_name = '', $method_name = '', $priority = 10 ) {
    remove_class_filter( $tag, $class_name, $method_name, $priority );
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。