I have the following PHP code:
$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');
I get the error that $cars in the foreach statement is undefined. However, as I understand it, the $cars array should be global in scope? If I pass the array into the function through the constructor it works fine. But I'm wondering why I can't access the array in this way.
global $cars;inside the function. Just above foreach loop