Array of PHP Objects

后端 未结 5 1370
孤城傲影
孤城傲影 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 06:53

    Although all the answers given are correct, in fact they do not completely answer the question which was about using the [] construct and more generally filling the array with objects.

    A more relevant answer can be found in how to build arrays of objects in PHP without specifying an index number? which clearly shows how to solve the problem.

    0 讨论(0)
  • 2020-12-02 06:54

    Yes, its possible to have array of objects in PHP.

    class MyObject {
      private $property;
    
      public function  __construct($property) {
        $this->Property = $property;
      }
    }
    $ListOfObjects[] = new myObject(1); 
    $ListOfObjects[] = new myObject(2); 
    $ListOfObjects[] = new myObject(3); 
    $ListOfObjects[] = new myObject(4); 
    
    print "<pre>";
    print_r($ListOfObjects);
    print "</pre>";
    
    0 讨论(0)
  • 2020-12-02 07:10

    Arrays can hold pointers so when I want an array of objects I do that.

    $a = array();
    $o = new Whatever_Class();
    $a[] = &$o;
    print_r($a);
    

    This will show that the object is referenced and accessible through the array.

    0 讨论(0)
  • 2020-12-02 07:16

    Yes.

    $array[] = new stdClass;
    $array[] = new stdClass;
    
    print_r($array);
    

    Results in:

    Array
    (
        [0] => stdClass Object
            (
            )
    
        [1] => stdClass Object
            (
            )
    
    )
    
    0 讨论(0)
  • 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";
    }
    
    0 讨论(0)
提交回复
热议问题