php:对象的数组(2)
一、代码一
1、“代码一”的源码
<?php
class NUM
{
public $number="";
public $number_class="";
}
class obj
{
public $v1 = "";
public $v2 = "";
}
for($i=0; $i<10; $i++)
{
$cat[$i] = new obj;
$nm[$i] = new NUM;
$nu[$i] = new NUM;
$nm[$i] -> number=$i;
$nm[$i] -> number_class = "red";
$nu[$i] -> number=$i*2;
$nu[$i] -> number_class = "green";
// 将“对象”赋予“成员变量”
$cat[$i]->v1 = $nm[$i];
$cat[$i]->v2 = $nu[$i];
}
foreach($cat as $ct)
{
echo "v1-number=" . $ct->v1->number ." v1-class=". $ct->v1->number_class . "\t";
echo "v2-number=" . $ct->v2->number ." v2-class=". $ct->v2->number_class . PHP_EOL;
}
?>
2、“代码一”的运行结果
二、代码二
1、“代码二”的源码
<!DOCTYPE html> <html> <body> <h1>PHP: Array Of Object</h1> <?php class NUM { public $number=""; public $number_class=""; } class obj { public $v1 = ""; public $v2 = ""; } for($i=0; $i<10; $i++) { $cat[$i] = new obj; // 创建临时对象,“代码”一和“代码二”的主要区别 $nm = new NUM; $nu = new NUM; $nm -> number=$i; $nm -> number_class = "red"; $nu -> number=$i*2; $nu -> number_class = "green"; // 将“对象”赋予“成员变量” $cat[$i]->v1 = $nm; $cat[$i]->v2 = $nu; } foreach($cat as $ct) { echo "v1-number=" . $ct->v1->number ." v1-class=". $ct->v1->number_class . "\t"; echo "v2-number=" . $ct->v2->number ." v2-class=". $ct->v2->number_class . PHP_EOL; } ?> </body> </html>
2、“代码二”的运行结果
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章的版权归属于【原创作者】; 转载或引用时请【保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/16557449.html