我有这个代码。我需要打印这些字符串。但是我不能在课外做出改变。所以我需要改变内部类的工作。字段必须保持私有。什么好主意吗?
class STUDENT {
private $nume,$prenume;
# Constructor
public function __construct($nume , $prenume){
$this->nume=$nume;
$this->prenume=$prenume;
}
}
$student = new STUDENT("one","two");
echo "student: ". $student ."<hr/>";
您必须定义__toString
方法。然后将echo
实例修改为string
:
class STUDENT {
private $nume,$prenume;
public function __construct($nume , $prenume){
$this->nume=$nume;
$this->prenume=$prenume;
}
public function __toString()
{
return '{nume:'.$this->nume.','.prenume:'.$this->prenume.'}';
}
}
$student = new STUDENT("one","two");
echo "student: ". $student ."<hr/>";
您需要使用getter和setter来读取和写入字段。这里有一个关于Getter和Setter的讨论?