PHP 对象数组 [英] Array of PHP Objects

查看:50
本文介绍了PHP 对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在寻找,但找不到一个简单问题的答案.是否可以在 PHP 中拥有一组对象?如:

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();    
$ar[]=$Obj1    
$ar[]=$obj2

出于某种原因,我无法在任何地方找到答案.我认为这是可能的,但我只需要确保.

For some reason I have not been able to find the answer anywhere. I assume it is possible but I just need to make sure.

推荐答案

找到诸如此类的一般性(和有些简单的问题)答案的最佳位置是阅读 PHP 文档.具体来说,您可以在 objects 上阅读更多内容.您可以在数组中存储 stdObject 和实例化对象.事实上,有一个过程叫做hydration' 用数据库行中的值填充对象的成员变量,然后将该对象存储在一个数组中(可能与其他对象一起)并返回给调用代码进行访问.

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.

-- 编辑 --

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

这篇关于PHP 对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆