PHP: Undefined property stdClass, but the property is already exists
Below is my class.
class MaterialType {
public $id;
public $name;
function getAllMaterialType() {
$query = "SELECT * FROM material_types";
$result = mysql_query($query);
开发者_Go百科 $arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = new MaterialType();
$arr[]->id = $row['m_type_id'];
$arr[]->name = $row['m_type_name'];
}
return $arr;
}
}
The problem is when I create object in an array like above, and display it using foreach
,
there are errors that say Undefined property stdClass
. I already defined the property that being used, so why these errors appear? Below is the code that I use to
display data.
$materialTypeObj = new MaterialType();
foreach($materialTypeObj->getAllMaterialType() as $mat) {
echo $mat->name;
}
Every time you do $array[] =
it inserts a new element in the end of an array. What you need to do is:
class MaterialType {
public $id;
public $name;
function getAllMaterialType() {
$query = "SELECT * FROM material_types";
$result = mysql_query($query);
$arr = array();
while($row = mysql_fetch_array($result)) {
$mat = new MaterialType();
$mat->id = $row['m_type_id'];
$mat->name = $row['m_type_name'];
$arr[] = $mat;
}
return $arr;
}
}
精彩评论