PHP 对象数组

所以我一直在寻找一个简单问题的答案。有没有可能在 PHP 中有一个对象数组?例如:

$ar=array();
$ar[]=$Obj1
$ar[]=$obj2

由于某种原因,我到处都找不到答案。我想这是有可能的,但我只是想确认一下。

384933 次浏览

Yes.

$array[] = new stdClass;
$array[] = new stdClass;


print_r($array);

Results in:

Array
(
[0] => stdClass Object
(
)


[1] => stdClass Object
(
)


)

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";
}

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.

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>";

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.

Another intuitive solution could be:

class Post
{
public $title;
public $date;
}


$posts = array();


$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';


$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';


foreach ($posts as $post) {
echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}

You can do something like this:

$posts = array(
(object) [
'title' => 'title 1',
'color' => 'green'
],
(object) [
'title' => 'title 2',
'color' => 'yellow'
],
(object) [
'title' => 'title 3',
'color' => 'red'
]
);

Result:

var_dump($posts);


array(3) {
[0]=>
object(stdClass)#1 (2) {
["title"]=>
string(7) "title 1"
["color"]=>
string(5) "green"
}
[1]=>
object(stdClass)#2 (2) {
["title"]=>
string(7) "title 2"
["color"]=>
string(6) "yellow"
}
[2]=>
object(stdClass)#3 (2) {
["title"]=>
string(7) "title 3"
["color"]=>
string(3) "red"
}
}