PHP: less ugly syntax for named parameters / arrays?

前端 未结 4 1353
暖寄归人
暖寄归人 2021-01-14 13:48

Here\'s what I am trying to accomplish:

function foo($args) {
 switch($args[\'type\']) {
  case \'bar\':
  bar($args[\'data\']);   // do something
  break;
          


        
相关标签:
4条回答
  • 2021-01-14 14:28

    There are no alternatives to constructing these nested arrays-- but there are options in how you can format your code that makes it readable. This is strictly preference:

    return array
    (
        'text' => array
        (
            'name'      => 'this is the second',
            'this'      => 'this is the third',
            'newarr'    => array
            (
                'example'
            ),
        )
    );
    
    
    // Or using the long way
    
    $array = array();
    
    $array += array
    (
        'this' => 'is the first array'
    );
    
    0 讨论(0)
  • 2021-01-14 14:38

    No. Alternative syntaxes for creating arrays have been proposed several times (the link lists 5 separate threads in the dev mailing list), but they were rejected.

    0 讨论(0)
  • 2021-01-14 14:47

    No, there is no "short-syntax" to write arrays nor objects, in PHP : you have to write all those array().
    (At least, there is no such syntax... yet ; might come in a future version of PHP ; who knows ^^ )

    But note that have too many imbricated arrays like that will makes things harder for people who will have to call your functions : using real-parameters means auto-completion and type-hinting in the IDE...

    0 讨论(0)
  • 2021-01-14 14:48

    You could create a JSON-encoded string and use json_decode() to convert it into a variable. This has syntax very similar to the Python-like syntax you mentioned.

    $argstr = '{"type" : "bar", "data" : [1, 2, 3], "data2" : [5, 10, 20]}';
    $buildArgs = json_decode($argstr, true);
    

    EDIT: Updated code to accommodate @therefromhere's suggestion.

    0 讨论(0)
提交回复
热议问题