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

2 Answers 2

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/>";  
Sign up to request clarification or add additional context in comments.

2 Comments

public function __toString(){ return $this->nume." ".$this->prenume; } this is wrong?
hmm. aparently student name needs to be red. can you help with that ?
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?

1 Comment

thank you. i used at other problems. i have some examples.. and i need to learn setter and getter and magic __set or __get.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.