php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #70231 Ability to set default params within a functions arguments as an array/object
Submitted: 2015-08-10 16:58 UTC Modified: -
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: mintystark at gmail dot com Assigned:
Status: Open Package: Arrays related
PHP Version: 7.0.0beta3 OS: Ubuntu
Private report: No CVE-ID: None
 [2015-08-10 16:58 UTC] mintystark at gmail dot com
Description:
------------
Currently if you want to send an array of parameters to a function, but have the function also use defaults in the array you then need to use array_merge in the function.  It would be useful if the function arguments could handle this automatically.

As far as the syntax goes I don't care, but I would really like this as it would reduce the amount of code I need to write and it would make it more readable. Plus allow for phpDocumentor and other features to utilize this.  Also I am sure you can make this more compatible with the compiler thus ran faster then using other methods like array_merge() etc.

Suggested Syntax Options:

function do_stuff($arr = {'a' => 'blue', 'b' => 'red', 'c' => 'black', 'd' => 'yellow'})

function do_stuff($arr = ['a' => 'blue', 'b' => 'red', 'c' => 'black', 'd' => 'yellow'])

function do_stuff($arr = &array('a' => 'blue', 'b' => 'red', 'c' => 'black', 'd' => 'yellow'))

Example Shown in the Test Script Below.



Test script:
---------------
function do_stuff($arr = {'a' => 'blue', 'b' => 'red', 'c' => 'black', 'd' => 'yellow'})
{
    return $arr;
}

print_r(do_stuff(array('b' => 'green', 'c' => null, 'd' => ''));



Expected result:
----------------
// Should output
// Array('a' => 'blue', 'b' => 'green', 'c' => 'black', 'd' => '');
// OR
// Object('a' => 'blue', 'b' => 'green', 'c' => 'black', 'd' => '');


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-08-26 17:19 UTC] jhdxr@php.net
I think it's a bad idea to pass all the params in one single argument.
 [2015-10-19 22:28 UTC] rahi at atsspec dot co
I'm with jhdxr, this is a bad idea for the following reasons:
- array_merge already provides a way to set default values of an array
- such an implementation easily gets out of hand when the array elements contain non primitive data types (objects)
- your use case is specific to array mashing, something the SPL collections/iterators are more suited for
- if you're using the $arr as parameters/flags and not plain data consider wrapping it in a class
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Oct 16 01:01:28 2024 UTC