lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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、“代码二”的运行结果

 

 

 

 

 

posted on 2022-08-06 16:54  lnlidawei  阅读(178)  评论(0编辑  收藏  举报