如果未将变量设置为参数,PHP中是否可以将变量传递给函数?

时间:2019-03-26 00:39:14

标签: php function parameters

在PHP中未将变量设置为参数时是否可以将变量传递给函数? 我的意思是这样的:

[weak self]

2 个答案:

答案 0 :(得分:0)

您可以使用func_num_args来检查函数参数的数量,如果结果为0,请从$GLOBALS数组中获取值,例如

def tree_iter_dfs(nested):
    for key, value in nested.iteritems():
        if isinstance(value, Mapping):
            yield value.items()
        else:
            yield [(key, value)]

# https://stackoverflow.com/a/952952/5309823
def flatten(l):
    return [item for sublist in l for item in sublist]

def tree_iter_bfs(nested):
    dfs = tree_iter_dfs(nested)
    return flatten(zip(*dfs))

print(list(tree_iter_bfs(data)))
# [('c', 1), ('e', 2), ('d', 3), ('f', 4)]

输出:

$foo = 4;

function myFunction () {
    if (!func_num_args()) {
        $input = $GLOBALS['foo'];
    }
    else {
        $input = func_get_arg(0);
    }
    echo "$input\n";
}

myFunction('hello');
myFunction();

Demo on 3v4l.org

答案 1 :(得分:0)

@Nick的答案应该起作用。这可能会更简单吗?

$pdo=PDOconnection;

function myFunction($input = null){
    if($input === null){
        $input=$GLOBALS['pdo'];
    }
}