php - 我可以集成具有相同内容、不同名称的函数吗?
我在一个类中有几个函数,它们本质上做同样的事情:
public function fn_a(){
return __FUNCTION__;
}
public function fn_b(){
return __FUNCTION__;
}
public function fn_c(){
return __FUNCTION__;
}
我需要这些函数保留它们当前的名称,所以我故意不这样做:
public function fn_($letter){
return __FUNCTION__.$letter;
}
我希望有某种方式来缩小这里的代码很冗长,因为它们都做同样的事情。最终的情况是这样的:
public functions fn_a, fn_b, fn_c() {
return __FUNCTION__;
}
另一种解决方案(如果适用)可能会执行类似 Class 的“扩展”之类的操作: fn_b、fn_c 扩展 fn_a
?
你们觉得怎么样?
I have a couple of functions inside a class that essentially do the same thing:
public function fn_a(){
return __FUNCTION__;
}
public function fn_b(){
return __FUNCTION__;
}
public function fn_c(){
return __FUNCTION__;
}
I need those functions to remain in their current names so I intentionally did not do:
public function fn_($letter){
return __FUNCTION__.$letter;
}
I was hoping for some sort of way to minify the verboseness of code here, since they all do the same. The ultimate situation would be something like this:
public functions fn_a, fn_b, fn_c() {
return __FUNCTION__;
}
Another solution, if applicable, might be doing something like Class's "extends":fn_b, fn_c extend fn_a
?
What do you think guys?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
任何类似于您建议的语法都是不可能的:如果您想要多个不同的函数,则必须声明所有这些函数。
不过,有一种可能是您的 fn_a、fn_b 和 fn_c 函数只是简单的包装器,包围着一个更复杂的函数:
当然,根据
fn_all
函数的长度,您可以减少代码重复量。另一个想法(不确定如何用方法来完成,所以我将用函数来演示)是使用闭包 - 这意味着 PHP >= 5.3
基本想法是你有第一个函数,它会返回另一个函数——它将绑定传递给第一个函数的参数:
首先,创建其他函数的函数:
然后,让我们使用创建者函数获得三个函数:
并且现在,调用这三个函数:
我们得到以下输出:
我从来不擅长解释匿名函数和闭包是如何工作的——但是在谷歌上搜索“闭包”应该可以帮助你理解;请注意,您可以阅读有关 Javascript 中的闭包的教程:其想法完全相同。
(而且,由于闭包是 PHP 中的新功能——随 PHP 5.3 一起出现——您将找不到与 Javascript 一样多的教程)
Any syntax like the one you suggested is not possible : if you want several distinct functions, you have to declare all those functions.
Still, a possibility could be that your fn_a, fn_b and fn_c functions just be simple wrappers arround a more complex one :
With that, depending on the length on the
fn_all
function, of course, you would reduce the amount of code-duplication.Another idea (not sure how this could be done with methods, so I'll demonstrate with functions) would be to use Closures -- which means PHP >= 5.3
The basic idea being that you'd have a first function, that would return another one -- which would bind the parameter passed to the first one :
First, the function that creates the others :
And, then, let's get three functions, using that creator one :
And now, calling those three functions :
We get the following output :
I've never good at explaining how anonymous functions and closures work -- but searching for "closure" on google should help you understand ; note that you can read tutorial about closures in Javascript : the idea is exactly the same.
(And, as closures are new in PHP -- arrived with PHP 5.3 -- you will not find as many tutorials as for Javascript)
就这样吗?
Like that?