好的,第一,我同意这是不礼貌的。此外,在 5.3 中,您可以使用带有 __call 魔术字的新闭包语法来将运算符用作函数(JS 风格)。
现在,如果我们想提供一种按照您的方式执行此操作的方法,我可以考虑使用 create_fnuction 和 __call 魔法。
基本上,您使用正则表达式模式将函数转换为兼容的字符串,并将它们放在私有成员中。比你使用 __call 方法来获取它们。我正在做一个小演示。
好的,课程就到这里。我从几周前看到的一个使用闭包来实现 JS 样式对象的课程中获得灵感:
/**
* supplies an interface with which you can load external functions into an existing object
*
* the functions supplied to this class will recive the classes referance as a first argument, and as
* a second argument they will recive an array of supplied arguments.
*
* @author arieh glazer <arieh.glazer@gmail.com>
* @license MIT like
*/
class Function_Loader{
/**
* @param array holder of genarated functions
* @access protected
*/
protected $_funcs = array();
/**
* loads functions for an external file into the object
*
* a note- the file must not contain php tags.
*
* @param string $source a file's loaction
*
* @access public
*/
public function load($source){
$ptrn = '/function[\s]+([a-zA-Z0-9_-]*)[\s]*\((.*)\)[\s]*{([\w\s\D]+)}[\s]*/iU';
$source = file_get_contents($source);
preg_match_all($ptrn,$source,$matches);
$names = $matches[1];
$vars = $matches[2];
$funcs = $matches[3];
for ($i=0,$l=count($names);$i<$l;$i++){
$this->_funcs[$names[$i]] = create_function($vars[$i],$funcs[$i]);
}
}
public function __call($name,$args){
if (isset($this->_funcs[$name])) $this->_funcs[$name]($this,$args);
else throw new Exception("No Such Method $name");
}
}
limitations- 1st,源不能有任何 php 标签。第二,功能永远是公开的。第三——我们只能模仿$this。我所做的是作为第一个参数 $this 传递,第二个是参数数组(这是第四个限制)。此外,您将无法从类中访问非公共成员和方法。
源文件示例:
function a($self,$arr=array()){
//assuming the object has a member called str
echo $self->str;
}
这对我来说是一个有趣的练习,但总的来说是一种不好的做法