简体   繁体   中英

How to create an array with objects in php

I want to have an array with objects. For example.

public $aCarObjects = array();
$aCars = array('Audi','BMW','Ford');

foreach($aCars as $car){
  array_push($aCarObjects, new Car($car));
}

// Simplified class
class Car implements C{
   private $carName;

  public function __construct($carName){
     $this->carName = $carName;
  } 
}
interface C {}

This is a very shortened version of what I am trying. The class Car contains some info about the car.

When I am using the Interface C in the Car class. I cannot add objects to the array. Why is that so?

This error has nothing to do with arrays, it's a class hoisting bug (feature?) which is fixed by moving your class definition above the call to new Car . Apparently, PHP does not hoist class definitions if they implement an interface .

Here's a minimal example of the phenomenon.

Works:

new Foo();
class Foo {}
interface Bar {} 

Doesn't:

new Foo(); # <-- error: Class 'Foo' not found
class Foo implements Bar {}
interface Bar {} 

Perhaps this is a candidate for PHP Sadness ?

Here's a working version of your code that also addresses a stray public keyword in line 1:

interface C {}

class Car implements C {
    private $carName;

    public function __construct($carName) {
        $this->carName = $carName;
    }
}

$aCarObjects = [];
$aCars = ['Audi', 'BMW', 'Ford'];

foreach ($aCars as $car) {
    array_push($aCarObjects, new Car($car));
}

print_r($aCarObjects);

Output:

Array
(
    [0] => Car Object
        (
            [carName:Car:private] => Audi
        )

    [1] => Car Object
        (
            [carName:Car:private] => BMW
        )

    [2] => Car Object
        (
            [carName:Car:private] => Ford
        )

)

Try it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM