Search code examples
phpjsonrubylanguage-comparisons

Ruby-like array arguments implementation in PHP


I program in PHP mostrly and Ruby sometimes I happen to be in need of a way to implements those "hash arguments" into my PHP funcions (Like, say, an HTML select helper)

draw_select :name => :id, :onclick => 'alert(this.value)'

The problem in PHP is that I would have to define an argument order to implement many possible attributes.

I have been thinking of just define 1 string argument and use json_decode() so i can pass arguments like this:

draw_select("'name': 'id', 'onclick': 'alert(this.value)' ")

the definition would be as follows:

function draw_select($string) {
// use json_decode here and pass them as variables
}

Do you know a smarter way to do this.. or you think that triying to to this in PHP does actually makes any sense at all?

Edited to add: I'm looking for a 'alternative' alternative to just pass a signle array as an argument like function(array(...))


Solution

  • PHP definitely is lacking some sugar in this aspect. I do a lot of Python also and I dearly miss named arguments when using PHP. With PHP, however, whenever I have a function that will need to accept a multitude of options I simply accept one or two required/important arguments, and an array for the rest:

    function draw_select($name, $options = array(), $html_options = array()) {
    
    }
    

    This is the way libraries like CodeIgniter and CakePHP handle the same <select> scenario.

    Personally, using JSON in this situation brings no real benefit when PHP's associative arrays are so powerful. Just stick to what the language gives you, and this is the way to do it with PHP.