全局作用域允许您在函数外部定义的函数中使用变量。例如
$a=1;
function $test(){
echo $a;
}
//outputs 1
Run Code Online (Sandbox Code Playgroud)
但是为什么如果我用数组定义一个变量,我不能以同样的方式使用它?
$test = array(
0=>'zero',
1=>'one',
2=>'two',
3=>'three',
);
function doesntWork($something){
echo "My favorite number is " . $test[$something];
}
//outputs My favorite number is 0
Run Code Online (Sandbox Code Playgroud)
如何将数组传递给函数而不必将数组重新复制到函数本身中。
任何解释将不胜感激谢谢
脚本 #1 不正确。它既不工作(函数 **$**test() {...}),也不输出“1”。和全局变量是不好的做法。将它们包装在一个类中与此无关。类不是与面向对象无关的随机问题的解决方案。
只需将 $a 作为参数传递:
<?php
$a=1;
function test($foo) {
echo 'number ' . $foo;
};
test($a);
// -> "number 1".
?>
Run Code Online (Sandbox Code Playgroud)
脚本#2:
<?php
$test = array(
0=>'zero',
1=>'one',
2=>'two',
3=>'three',
);
function doesntWork($test, $something){
echo "My favorite number is " . $test[$something];
}
doesntWork($test, mt_rand(0,3));
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13354 次 |
| 最近记录: |