In the foreach loop, $ p [] = $ MaterialType's question class & nbsp; so_getMaterialType {var & nbsp; $ CreateTime & nbsp; = & nbsp; ''; var & nbsp; $ IsDefault & nbsp ;=& nbsp; ''' $ p [] = $ MaterialType in The foreach loop
Class so_getMaterialType
{
Var $ CreateTime = '';
Var $ IsDefault = '';
Var $ UpdateTime = '';
}
$ P = array ();
$ SQL = 'select * from tb where lid <50 ';
$ Re_materialTypeID = $ db-> getAll ($ SQL );
Foreach ($ re_materialTypeID as $ key => $ val)
{
$ GetMaterialType = new so_getMaterialType; // why do I apply for a new application every time, instead of applying for a new one outside the loop ??
$ GetMaterialType-> CreateTime = $ val ['createtime'];
$ GetMaterialType-> IsDefault = $ val ['isdefault'];
$ GetMaterialType-> UpdateTime = $ val ['updatetime'];
$ P [] = $ getMaterialType;
}
Var_dump ($ p );
Return $ p;
/* -------- What is the difference between this writing method and above ?? -----------*/
$ GetMaterialType = array ();
$ GetMaterialType [] = new so_getMaterialType;
$ SQL = 'select * from tb where lid <50 ';
$ Re_materialTypeID = $ db-> getAll ($ SQL );
Foreach ($ re_materialTypeID as $ key => $ val)
{
$ GetMaterialType [$ key]-> CreateTime = $ val ['createtime'];
$ GetMaterialType [$ key]-> IsDefault = $ val ['isdefault'];
$ GetMaterialType [$ key]-> UpdateTime = $ val ['updatetime'];
}
Var_dump ($ getMaterialType );
Return $ getMaterialType;
------ Solution --------------------
The first code
$ P is an array containing several so_getMaterialType objects.
Second code
$ The first element of getMaterialType is the so_getMaterialType object, and the rest are stdClass objects.
Obviously, what you need is the result of the first writing method.
Therefore
class so_getMaterialType {
var $CreateTime = '';
var $IsDefault = '';
var $UpdateTime = '';
function __construct($a) {
foreach($a as $k->$v) $this->$k = $v;
}
}
$p = array();
$sql = 'SELECT * from tb where lid<50';
$re_materialTypeID = $db->getAll($sql);
foreach($re_materialTypeID as $key => $val) {
$p[] = new so_getMaterialType($val) ;
}
------ Solution --------------------
$getMaterialType = new so_getMaterialType ;
The new keyword generates a memory space. the memory address is assigned to $ getMaterialType, that is, $ getMaterialType is an address pointing to the previous memory space. Therefore, the object $ getMaterialType is a pointer.
$p[] = $getMaterialType ;
Because the value of $ getMaterialType is not changed in the first method, all elements in all p [] point to the same memory address, and the data is of course the same.
In the second write method, a new memory space is generated each time and the address is assigned to $ getMaterialType. Therefore, elements in p [] point to different memory spaces.
To put it simply:
Only $ getMaterialType = ××× changes the value of $ getMaterialType. $ getMaterialType-> attribute = ××× does not change the value of $ getMaterialType.