Removing a function at runtime in PHP (without the runkit extension)

前端 未结 9 1465
逝去的感伤
逝去的感伤 2020-12-09 16:33

I know this question seems hacky and weird, but is there a way to remove a function at runtime in PHP?

I have a recursive function declared in a \"if\" block and wan

9条回答
  •  心在旅途
    2020-12-09 16:52

    Initial function definition looks like:

    // includes/std_functions.php
    if (! function_exists('the_function')) {
      function the_function() {
        global $thefunction;
        return call_user_func_array($thefunction, func_get_args());
      }
      $GLOBALS['thefunction'] = function() {
        echo 'foo';
      };
    }
    

    if you have a test condition that allows you to rewrite code:

    // somewhere in your code
    if () {
      $GLOBALS['thefunction'] = function() {
        echo 'bar';
      };
    }
    

    if you are overloading in another include that will be loaded before or after the original file:

    // includes/custom_functions.php
    if (! function_exists('the_function')) {
      function the_function() {
        global $thefunction;
        return call_user_func_array($thefunction, func_get_args());
      }
    }
    $GLOBALS['thefunction'] = function() {
      echo 'bar';
    };
    

提交回复
热议问题