>我有以下内容:
class bar {
function __construct(){
// set $a_from_fire to $a from fire() method arg
// set $b_from_fire to $b from fire() method arg
}
}
class foo extends bar {
function fire ($a, $b){
}
}
我需要使用 foo->fire() 中的参数设置 $a_from_fire 和 $b_from_fire
因此,如果我这样做:
$test = new foo;
$test->fire(1, 2);
将设置这些变量:
$a_from_fire == 1; // true
$b_from_fire == 2; // true
我认为你不能以任何"正确"的方式做到这一点。我的第一个想法是使用__call
,但这当然只适用于未定义的函数。
而且实际上没有任何方法可以动态重命名方法,除非您已经在使用 RunKit
。(不是我知道或无论如何都能找到的)。
如果纯粹出于调试目的,则可以设置自己的类自动加载器来预处理文件,更改方法名称,然后在父类上使用__call
magic 方法。
spl_autoload_register(function($class){
$hackPath = '/home/_classes/'.$class;
if (!file_exists($hackPath)){
$realPath = '/home/classes/'.$class;
$file = file_get_contents($realPath);
$processedContent = //use regex or something to prepend all function names with an _.
file_put_contents($hackPath,$processedContent);
}
require_once $hackPath;
});
然后在您的父类中
class parent {
public function __call($funcName,$arguments){
$this->myLogFunc($funcName,$arguments);
//since you prepended with an underscore
return call_user_func_array('_'.$funcName,$arguments);
}
这是完成您要求的一种糟糕的方法,但它可能会起作用。文件的预处理可能很慢,但只有在原始文件发生更改时才需要执行此操作(您可以使用filemtime
来检查它是否已更改)。
这
是不可能的,因为__construct()
是在对象首次实例化时调用的,因此fire($a, $b)
将始终在__construct()
之后运行
如果您只想在调用fire()
时设置变量,只需执行以下操作:
class bar {
protected $a_from_fire;
protected $b_from_fire;
}
class foo extends bar {
public function fire($a, $b) {
$this->a_from_fire = $a;
$this->b_from_fire = $b;
}
}