I have this code. And i need to print those strings. But i can't make changes outside the class. So i need to change inside class to work. The fields must remain private. Any ideas?
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/>";
You have to define __toString
method. Then you can echo
instance as 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/>";
You need to use getters and setters so the fields can be read and written. Here's a discussion on the subject: Getter and Setter?