我有一個PHP函數,傳遞變量到PHP方法
func($c) {
global $a,$b;
//Do something
}
我這樣稱呼它,
$c = "Test";
func($c);
但在某些情況下,我需要傳遞一個額外的參數$ B,它不應該把全局變量值覆蓋,所以我想這一點,
func($c,$b = $b,$a = $a) {
//Do something
}
但是在默認設置PHP變量是不允許的。所以好心幫我在這裏...
我有一個PHP函數,傳遞變量到PHP方法
func($c) {
global $a,$b;
//Do something
}
我這樣稱呼它,
$c = "Test";
func($c);
但在某些情況下,我需要傳遞一個額外的參數$ B,它不應該把全局變量值覆蓋,所以我想這一點,
func($c,$b = $b,$a = $a) {
//Do something
}
但是在默認設置PHP變量是不允許的。所以好心幫我在這裏...
所以你想使用全局變量作爲函數參數的默認值? 假設null
從不作爲有效參數傳遞,您可以使用以下代碼。
function func($c, $b = null, $a = null) {
if($b === null) $b = $GLOBALS['b'];
if($a === null) $a = $GLOBALS['b'];
}
<?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);
?>
月,這將幫助你。
<?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
);
我不明白你的問題?請詳細說明你想要做什麼或實現什麼? –
你發佈的代碼甚至不是有效的PHP代碼....除此之外,全局變量通常是不好的。 – ThiefMaster