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

查看:111
本文介绍了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文档。具体到你的情况,你可以了解更多关于对象。您可以在阵列中的存储stdObject和实例化对象。实际上,有称为'<一流程href=\"http://www.doctrine-project.org/documentation/manual/1_2/zh/working-with-models#fetching-objects\">hydration'其与值填充的对象的成员变量从数据库行,那么该对象被存储在一个阵列(可能与其他对象),并返回到调用code代表访问

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天全站免登陆