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.
Along with Exprator's solution, you could also pass the $cars
array to the function like this.
function getCarsByMake($carMake, $cars){
foreach($cars as $car){
if($car->make == $carMake){
echo 'Car: ' . $car->make . ' ' . $car->model . "<br>";
}
}
}
getCarsByMake('Ford', $cars);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With