是否可以在 PHP 中咖喱方法调用?

2021-12-24 00:00:00 php soap currying

我有一个为 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.

相关文章