如何在PHP中在运行时禁用用户定义的函数和类?

时间:2015-05-26 15:32:38

标签: php

是否可以在运行时禁用用户定义的函数和/或类?我不想重载函数,只需像disable_functionsdisable_classes指令一样禁用它。

1 个答案:

答案 0 :(得分:0)

也许您必须包装要禁用的功能。

$disabled_funcs = [];

// original code
function func ($msg) {
  echo "$msg\n";
}

//The wrapped one:

function _func () {
  global $disabled_funcs;
  $func = substr (__FUNCTION__, 1);
  if (isset($disabled_funcs[$func]))
    throw new Exception ("Function $func is disabled.");
  return call_user_func_array ($func, func_get_args());
}

function disable_func ($name) {
    global $disabled_funcs;
    $disabled_funcs[$name] = 1;
}

function enable_func ($name) {
    global $disabled_funcs;
    if (isset($disabled_funcs[$name]))
        unset ($disabled_funcs[$name]);
}

//Call the function:
_func ("Func not disabled.");
disable_func ("func");
try {
    _func ("Exception will be raised, this will not be displayed");
} catch (Exception $e) {
    echo $e->getMessage() . PHP_EOL;
}
enable_func ("func");
_func ("Func enabled");

请参阅小提琴:http://ideone.com/yQaAtq