PHP中的数组对象 [英] Array Object In Php
本文介绍了PHP中的数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将学生对象存储到数组中.我尝试使用下面的代码.但它始终显示数组计数为0
i want to store Student Object to array. and i try to do with below code. but it always show array count as 0
class Student
{
$StudID = 0;
$Name = null;
}
class Students
{
static private $StudentData = array();
static public function AddNewStudent($id,$name)
{
echo("AuctionID :".$AuctionID."<br/>");
try{
$objstd = new Student();
$objstd->StuID = $id;
$objstd->Name = &name;
array_push($StudentData, $objstd);
}
catch (Exception $e)
{
echo("Error".$e->getMessage());
}
}
static public function TotalStudent()
{
return count($StudentData);
}
}
Students::AddNewStudent(1,"name");
Students::AddNewStudent(2,"name2");
Students::AddNewStudent(3,"name3");
echo('Total auction running : '.Students::TotalStudent().'<br/>');
当我尝试显示数组计数时,它显示为0.我想将所有学生数据存储在静态列表中或之后,当我想查看列表之后,我只能从静态类中获取列表...
when i try to show array count it shows 0. i want to store all student data in static list or then after when ever i want to see the list i get the list from static class only...
推荐答案
因为您正在创建一个新数组,而不是引用您声明的数组.使用 self
关键字引用您的静态对象属性:
Because you're creating a new array instead of referencing the one you declared. Use the self
keyword to reference your static object property:
class Students
{
static private $StudentData = array();
static public function AddNewStudent($id,$name)
{
echo("AuctionID :".$AuctionID."<br/>");
try{
$objstd = new Student();
$objstd->StuID = $id;
$objstd->Name = &name;
array_push(self::$StudentData, $objstd);
}
catch (Exception $e)
{
echo("Error".$e->getMessage());
}
}
static public function TotalStudent()
{
return count(self::$StudentData);
}
}
这篇关于PHP中的数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文