一个人将如何重写以下..。
class crunch {
private $funcs = [];
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($data);
}
}
}
$db = 'dbhandle';
$crunch = new crunch();
$crunch->set('myfunction', function($data) {
global $db;
echo 'db = '. $db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd']);
..。正确地输出..。
db = dbhandle
[123,"asd"]
..。在动态添加函数中使用频繁使用的变量/句柄时,要删除丑陋的global
需求吗?
通常,我会将全局构造定义为以下内容,但可以理解,这与致命错误Uncaught Error: Using $this when not in object context
失败有关.
class crunch {
private $db;
private $funcs = [];
public function __construct($db) {
$this->db = $db;
}
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($data);
}
}
}
$db = 'dbhandle';
$crunch = new crunch($db);
$crunch->set('myfunction', function($data) {
echo 'db = '. $this->db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd']);
实现目标最干净的方法是什么?
编辑:正如@Raj深处所指出的,我可以在$crunch->set()
函数中传递$db。但是我想避免这种情况,因为每个动态函数都可以引用从这些私有变量中的0到5个之间的任何地方,而且使用每个$crunch->set()
调用所有5都是不雅观的。
发布于 2016-10-16 15:45:16
与创建私有实例变量$db
不同,只需将该变量传递给call()
方法即可。您的代码应该如下所示:
class crunch {
private $funcs = [];
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false, $db) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($data, $db);
}
}
}
$db = 'dbhandle';
$crunch = new crunch();
$crunch->set('myfunction', function($data, $db){
echo 'db = '. $db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd'], $db);
输出:
db = dbhandle
[123,"asd"]
更新(1):
如果您只想将$db
作为实例变量访问,则解决方案将如下所示:
class crunch {
public $db;
private $funcs = [];
public function __construct($db) {
$this->db = $db;
}
public function set($name, $function) {
$this->funcs[$name] = $function;
}
public function call($function, $data=false) {
if (isset($this->funcs[$function]) && is_callable($this->funcs[$function])) {
return $this->funcs[$function]($this, $data);
}
}
}
$db = 'dbhandle';
$crunch = new crunch($db);
$crunch->set('myfunction', function($crunch, $data) {
echo 'db = '. $crunch->db .'<br>'. json_encode( $data );
});
$crunch->call('myfunction', [123,'asd']);
注意到,必须使$db
成为公共成员变量,否则在调用set()
方法时将无法访问它。
https://stackoverflow.com/questions/40071911
复制相似问题