我有以下PHP代码:
$car1 = new Car('Ford','Fusion');
$car2 = new Car('Chevy', 'Avalanche');
$car3 = new Car('Ford', 'F150');
$cars = array($car1, $car2, $car3);
function getCarsByMake($carMake){
foreach($cars as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
getCarsByMake('Ford');
我收到$cars
语句中foreach
未定义的错误。但是,据我所知,$cars
数组的范围应该是全局的?如果我通过构造函数将数组传递给函数,它可以正常工作。但我想知道为什么我不能以这种方式访问阵列。
答案 0 :(得分:6)
除了Exprator的解决方案,您还可以将$cars
数组传递给这样的函数。
function getCarsByMake($carMake, $cars){
foreach($cars as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
getCarsByMake('Ford', $cars);
答案 1 :(得分:3)
function getCarsByMake($carMake){
global $cars;
foreach($cars as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
getCarsByMake('Ford');
因为函数没有得到$cars
,你需要在函数内全局访问它
答案 2 :(得分:3)
您有两种选择。
添加global
关键字
function getCarsByMake($carMake){
global $cars;
foreach($cars as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
使用$GLOBALS
数组:
function getCarsByMake($carMake){
foreach($GLOBALS["cars"] as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
虽然我仍然建议将其作为显式参数传递,因为这样可以使代码更具可读性和可维护性,恕我直言。
答案 3 :(得分:0)
您可以在全球范围内拨打$ cars,但您也可以根据您的代码尝试其他方式.Ex:
$car1 = new Car('Ford','Fusion');
$car2 = new Car('Chevy', 'Avalanche');
$car3 = new Car('Ford', 'F150');
$cars = array($car1, $car2, $car3);
function getCarsByMake($carMake,$cars){
foreach($cars as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
getCarsByMake('Ford',$cars);