首页 / PHP / PHP:将函数分配给类方法
PHP:将函数分配给类方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP:将函数分配给类方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2372字,纯文字阅读大概需要4分钟。
内容图文
![PHP:将函数分配给类方法](/upload/InfoBanner/zyjiaocheng/661/b104128378634a71a3852e2564114c13.jpg)
如何在PHP的类中将函数分配给方法?我尝试了以下方法:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar')
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName))
continue;
$this->{$functionName}() = function($params){ //should create the methods "foo" and "bar"
echo $variable; //should echo 'blablabla' (I know that the variable was declared outside this function, but how can I access it anyway?)
}; //the error points to here
}
}
}
但是这段代码给了我这个错误:
Fatal error: Can't use method return value in write context
有谁知道我如何将匿名函数分配给类方法,同时还能访问该函数之外的变量?
解决方法:
您正在做foreach($functionNames as $functionName){,这意味着$functionName是字符串,而不是数组.因此,请勿使用$functionName [0].
method_exists具有2个参数.一个是对象,另一个是方法名称.它应该是:
method_exists($this, $functionName)
至于创建函数,则不需要在=的左侧添加().它应该是:
$this->$functionName = function($params) use($variable){
echo $variable;
};
需要use($variable)告诉PHP在函数内使用该变量.这就是闭包在PHP中的工作方式,它与其他语言不同.
因此,您的课程应如下所示:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar');
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName)){
continue;
}
$this->$functionName = function($params) use($variable){
echo $variable;
};
}
}
}
这里的问题是,以这种方式创建函数,您实际上不是在创建类方法,而是在创建包含函数的类变量.
因此,您需要这样称呼它:
$test = new Something;
$foo = $test->foo;
$foo('abc');
您不能只执行$test-> foo(‘abc’);.
编辑:您可以做的另一件事是使用PHP的__call“魔术方法”.每当您执行-> funcName()时,无论该方法是否存在,都将运行该命令.使用该方法,您可以仅查看所调用的方法是“ foo”还是“ bar”.请参阅以下示例:
class Something{
private $variable;
public function __construct(){
$this->variable = 'blablabla';
}
public function __call($name, $params=array()){
if(method_exists($this, $name)){
// This makes sure methods that *do* exist continue to work
return call_user_func(array($this, $name), $params);
}
else{
$functionNames = array('foo', 'bar');
if(in_array($name, $functionNames)){
// You called ->foo() or ->bar(), so do something
// If you'd like you can call another method in the class
echo $this->variable;
}
}
}
}
现在,您可以执行以下操作:
$test = new Something;
$test->foo('abc'); // Will echo "blablabla"
内容总结
以上是互联网集市为您收集整理的PHP:将函数分配给类方法全部内容,希望文章能够帮你解决PHP:将函数分配给类方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。