2011-10-05 67 views
0

我有一个PHP函数,传递变量到PHP方法

func($c) { 

global $a,$b; 

//Do something 

} 

我这样称呼它,

$c = "Test"; 
func($c); 

但在某些情况下,我需要传递一个额外的参数$ B,它不应该把全局变量值覆盖,所以我想这一点,

func($c,$b = $b,$a = $a) { 

//Do something 

} 

但是在默认设置PHP变量是不允许的。所以好心帮我在这里...

+0

我不明白你的问题?请详细说明你想要做什么或实现什么? –

+0

你发布的代码甚至不是有效的PHP代码....除此之外,全局变量通常是不好的。 – ThiefMaster

回答

3

所以你想使用全局变量作为函数参数的默认值? 假设null从不作为有效参数传递,您可以使用以下代码。

function func($c, $b = null, $a = null) { 
    if($b === null) $b = $GLOBALS['b']; 
    if($a === null) $a = $GLOBALS['b']; 
} 
2

使用func_get_args

<?php 
function foo() 
{ 
    $numargs = func_num_args(); 
    echo "Number of arguments: $numargs<br />\n"; 
    if ($numargs >= 2) { 
     echo "Second argument is: " . func_get_arg(1) . "<br />\n"; 
    } 
    $arg_list = func_get_args(); 
    for ($i = 0; $i < $numargs; $i++) { 
     echo "Argument $i is: " . $arg_list[$i] . "<br />\n"; 
    } 
} 

foo(1, 2, 3); 
?> 
0

月,这将帮助你。

<?php 

    function doWork($options) 
    { 
     extract(
      merge_array(
       array(
        'option_1' => default_value, 
        'option_2' => default_value, 
        'option_3' => default_value, 
        'option_x' => default_value 
       ), 
       $options 
      ) 
     ); 

     echo $option_1; // Or do what ever you like with option_1 
    } 

    $opts = array(
     'option_1' => custom_value, 
     'option_3' => another_custom_value 
    );