Is it possible to curry method calls in PHP?

前端 未结 8 2452
日久生厌
日久生厌 2020-12-06 01:17

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

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 01:58

    This answer Is it possible to curry method calls in PHP? doesn't show Currying. That answer shows partial application. A nice tutorial which explains the difference between those concepts can be seen here: http://allthingsphp.blogspot.com/2012/02/currying-vs-partial-application.html

    This is Currying:

    function sum3($x, $y, $z) {
        return $x + $y + $z;
    }
    
    // The curried function    
    function curried_sum3($x) {
        return function ($y) use ($x) {
            return function ($z) use ($x, $y) {
                return sum3($x, $y, $z);
            };
        };
    }
    

    Invoking the curried function in PHP 7

    $result = curried_sum3(1)(2)(3); 
    var_dump($result); // int 6
    

    Invoking the curried function in PHP 5

    $f1 = curried_sum3(6);
    $f2 = $f1(6);
    $result = $f2(6);
    var_dump($result);
    
    //OUTPUT:
    int 18
    

    This is Partial application:

    function sum3($x, $y, $z) {
        return $x + $y + $z;
    }
    
    function partial_sum3($x) {
        return function($y, $z) use($x) {
            return sum3($x, $y, $z);
        };
    }
    
    //create the partial
    $f1 = partial_sum3(6);
    //execute the partial with the two remaining arguments
    $result = $f1(6, 6);
    
    var_dump($result);
    
    //OUTPUT:
    int 18
    

提交回复
热议问题