phpsoapcurrying

Is it possible to curry method calls in PHP?


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?


Solution

  • 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: 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');
    

    But the other suggestions using __call() and a wrapper class may be better if you want to "enhance" a complete class.