将可变数量的参数传递给php函数的最佳方法

时间:2014-03-29 09:30:10

标签: php

将可变数量的参数传递给php函数的最佳方法是什么?我的意思是,假设我有以下内容:

function my_func($a, $b, $c) {
    $q = 'SELECT ' . $a . ' FROM ' . $b . ' WHERE status IS NULL';
}

my_func('id', 'table');
my_func('id', 'table', ' AND x = 1');

我读过func_get_arg(),但如果我在第一种情况下拨打func_get_arg(2),我会收到Argument 2 not passed to function错误。

重要提示:此查询不是使用用户传递的参数执行的,因此没有注入hazzards!它由我给出的受控参数执行,其功能是检查该值是否在外键组合中有效!所以请不要讽刺“注射天堂”的评论,谢谢。

2 个答案:

答案 0 :(得分:2)

我不知道它是否最好,但我喜欢将数组作为参数传递,然后在我的函数中使用它。这是一个例子:

function my_query($query = array())
{
    // select and from are required to exist
    if(!empty($query) && array_key_exists('select', $query) && array_key_exists('from', $query))
    {
        $q  = "select {$query['select']}";
        $q .= " from {$query['from']}";

        foreach($query as $key => $val)
        {
            // Don't want to include select and from once again (also do not unset before in case need to run all of this once again)
            if($key != 'select' && $key != 'from')
            {
                // Search if key has underscore and replace it with space for valid query
                if(strpos($key, '_') !== false)
                    $key = str_replace('_', ' ', $key);

                // Build query with spaces and all
                $q .= " " . $key . " " . $val;
            }
        }

        // Run query here using $q
    }
}

你可以随意传入数组:

$query = array(
    'select'    => '*',
    'from'      => 'users',
    'where'     => 'age > 25',
    'order by'  => 'id'
);

// Or 
$query = array();

$query['select']    = '*';
$query['from']  = 'users';
$query['where'] = 'age > 25';
$query['order_by']  = 'id';

my_query($query);

// Would return us something like this
string(46) "select * from users where age > 25 order by id"

但是使用它你必须在数组中保持正确的顺序,或者在函数中编写排序和验证代码。

答案 1 :(得分:1)

既然你已经提到过你的函数没有处理用户传递的参数..我建议你这样做..

仅供参考:我刚刚在其中使用echo用于演示目的..您可以稍后更改。

<?php
function my_func() {

    echo $q = 'SELECT ' . func_get_arg(0) . ' FROM ' . func_get_arg(1) . ' WHERE status IS NULL';
}

my_func('id', 'table');

以上显示...

SELECT id FROM table WHERE status IS NULL

参数从0索引开始,所以你应该做.. func_get_arg(1)来得到第二个参数。

相关问题