0

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/>";  

2 Answers2

1

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?

Community
  • 1
  • 1
Dave Morrissey
  • 4,371
  • 1
  • 23
  • 31
  • thank you. i used at other problems. i have some examples.. and i need to learn setter and getter and magic __set or __get. – Albert Staize Jun 15 '14 at 12:59
1

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/>";  
hindmost
  • 7,125
  • 3
  • 27
  • 39