PHP中类似Ruby的数组参数实现 [英] Ruby-like array arguments implementation in PHP

查看:115
本文介绍了PHP中类似Ruby的数组参数实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最常使用PHP编程,而Ruby有时却需要一种将这些哈希参数"实现到我的PHP函数中的方法(例如HTML选择帮助器)

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)'

PHP中的问题是我必须定义一个参数顺序才能实现许多可能的属性.

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

我一直在考虑只定义1个字符串参数并使用json_decode(),这样我就可以传递这样的参数:

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)' ")

定义如下:

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

您知道更聪明的方法吗?.还是您认为在PHP中进行此操作实际上没有任何意义吗?

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?

编辑后添加:我正在寻找一种替代"替代方法,只是将信号数组作为参数传递给函数(array(...))

推荐答案

PHP在这方面肯定缺少一些支持.我也做很多Python,在使用PHP时,我非常想念命名参数.但是,使用PHP时,只要我有一个需要接受多个选项的函数,我就只接受一个或两个必需的/重要的参数,剩下的则是一个数组:

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()) {

}

这是诸如CodeIgniter和CakePHP之类的库处理相同<select>方案的方式.

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

就个人而言,当PHP的关联数组如此强大时,在这种情况下使用JSON并不会带来真正的好处.只需坚持该语言为您提供的功能,这就是使用PHP做到这一点的方法.

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.

这篇关于PHP中类似Ruby的数组参数实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆