Named Arguments in PHP

前端 未结 3 1277
自闭症患者
自闭症患者 2020-12-12 05:09

In C#, there is a new feature coming with 4.0 called Named Arguments and get along well with Optional Parameters.

private static void writeSomething(int a =          


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 05:29

    As you found out, named arguments don't exist in PHP.


    But one possible solution would be to use one array as unique parameter -- as array items can be named :

    my_function(array(
        'my_param' => 10, 
        'other_param' => 'hello, world!', 
    ));
    


    And, in your function, you'd read data from that unique array parameter :

    function my_function(array $params) {
    
        // test if $params['my_param'] is set ; and use it if it is
        // test if $params['other_param'] is set ; and use it if it is
        // test if $params['yet_another_param'] is set ; and use it if it is
        // ...
    
    }
    


    Still, there is one major inconvenient with this idea : looking at your function's definition, people will have no idea what parameters it expects / they can pass.

    They will have to go read the documentation each time they want to call your function -- which is not something one loves to do, is it ?

    Additionnal note : IDEs won't be able to provide hints either ; and phpdoc will be broken too...

提交回复
热议问题