Is it possible to curry method calls in PHP?(是否可以在 PHP 中咖喱方法调用?)
问题描述
我有一个为 WSDL 文件生成的 SoapClient 实例.除了其中一个方法调用之外的所有方法都需要传递用户名和密码 id.
I have a SoapClient instance generated for a WSDL file. All except one of the method invocations require the username and the password to be passed id.
有什么办法可以将方法调用柯里化,这样我就可以省略用户名和密码吗?
Is there any way of currying the method calls so that I can omit the username and password?
推荐答案
从 php 5.3 开始,您可以存储 变量中的匿名函数.这个匿名函数可以使用一些预定义的参数调用原始"函数.
As of php 5.3 you can store an anonymous function in a variable. This anonymous function can call the "original" function with some predefined parameters.
function foo($x, $y, $z) {
echo "$x - $y - $z";
}
$bar = function($z) {
foo('A', 'B', $z);
};
$bar('C');
您还可以使用闭包来参数化匿名函数的创建
edit: You can also use a closure to parametrise the creation of the anonymous function
function foo($x, $y, $z) {
echo "$x - $y - $z";
}
function fnFoo($x, $y) {
return function($z) use($x,$y) {
foo($x, $y, $z);
};
}
$bar = fnFoo('A', 'B');
$bar('C');
edit2:这也适用于对象
edit2: This also works with objects
class Foo {
public function bar($x, $y, $z) {
echo "$x - $y - $z";
}
}
function fnFoobar($obj, $x, $z) {
return function ($y) use ($obj,$x,$z) {
$obj->bar($x, $y, $z);
};
}
$foo = new Foo;
$bar = fnFoobar($foo, 'A', 'C');
$bar('B');
但是如果您想增强"一个完整的类,使用 __call() 和包装类的其他建议可能会更好.
But the other suggestions using __call() and a wrapper class may be better if you want to "enhance" a complete class.
这篇关于是否可以在 PHP 中咖喱方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 PHP 中咖喱方法调用?


基础教程推荐
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01