Array of PHP Objects

后端 未结 5 1372
孤城傲影
孤城傲影 2020-12-02 06:29

So I have been searching for a while and cannot find the answer to a simple question. Is it possible to have an array of objects in PHP? Such as:

$ar=array()         


        
5条回答
  •  情深已故
    2020-12-02 07:17

    The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

    -- Edit --

    class Car
    {
        public $color;
        public $type;
    }
    
    $myCar = new Car();
    $myCar->color = 'red';
    $myCar->type = 'sedan';
    
    $yourCar = new Car();
    $yourCar->color = 'blue';
    $yourCar->type = 'suv';
    
    $cars = array($myCar, $yourCar);
    
    foreach ($cars as $car) {
        echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
    }
    

提交回复
热议问题