简体   繁体   English

用PHP中的无法编辑的方法挂钩函数

[英]Hook a function with uneditable method in PHP

I want to know if this is possible. 我想知道是否有可能。

Imagine that I am using a PHP library Class which I can not modify. 想象一下,我使用的是无法修改的PHP库类。 However I want to hook to its method somehow, that whenever it's called, my custom code executes. 但是,我想以某种方式挂接到它的方法,无论何时调用它,我的自定义代码都会执行。

For example: 例如:

<?php

function uneditable() {
    // does something
}

// my code:
if(<uneditable is called>){
    // do this
}

Is it possible in PHP somehow? 是否有可能以某种方式在PHP中?

Note: I'm trying to do this with WordPress, as I have to detect execution of some method in a third party plugin which doesn't provide hooks to the endpoint that i'm trying to hook into. 注意:我正在尝试使用WordPress执行此操作,因为我必须检测第三方插件中某些方法的执行,该第三方插件不提供我尝试连接的端点的钩子。 I don't want to edit the plugin itself as it will get updated anytime and my code will be gone. 我不想编辑插件本身,因为它将随时更新,并且我的代码也将消失。

Thank and Regards. 谢谢和问候。

As it is wordpress you can use the Wordpress hook . 由于它是wordpress,因此可以使用Wordpress挂钩

Here is an example. 这是一个例子。

<?php

 /**
  * Define the action and give functionality to the action.
  */
 function uneditable() {
   do_action( 'uneditable' );
 }

 /**
  * Register the action with WordPress.
  */
 add_action( 'uneditable', 'uneditable_hook' );
 function uneditable_hook() {
   echo 'This is a custom action hook.';
 }

You can read more about add_action and do_action 您可以阅读有关add_actiondo_action的更多信息

What you need is abstract method in abstract class. 您需要的是抽象类中的抽象方法。 That will force the child class to implement the method. 这将迫使子类实现该方法。

abstract class A {


abstract function a() {}

}

class B extends A {

function a () {


// write your code here.
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM