PHP exception handling issues

There is an open book survey for the work app I am doing, and he clearly highlighted a flaw in my php knowledge.

Note that I am not asking for an answer directly, I am asking you to show that I misunderstand / don’t know how to answer it. The question arises:

3. Finish the following class to print "Person->name has been zapped" when the following is executed on a Person object: print $person; class Person{ private $name = ''; public function __construct($name){ $this->name = $name; } } $person = new Person('fred'); print $person; // fred has been zapped 

Now either there is a way to add exception handling to the class (although I would have thought that “printing” would be the one that throws the exception, or I just misunderstood the question. I know (from a quick test), resulting in printing in the try file .. catch still crashes the program with a "perceptible fatal error" (my catch did not work).

What should i read?

David

+4
source share
2 answers

Hmm, they seem to be looking for knowledge of the PHP5 classes. I would suggest taking a look at PHP's magic methods to better understand how to accomplish what you are trying to do.

Basically, you want to have a printed representation of the object in question.

+4
source

When you try to echo / output an object, the __ toString () magic method is called if it is defined for the class that the object is an instance of.

Here you will need to modify the class to add a definition of this __toString method, which will return the name, and part of the string has been "noticed":

 class Person{ private $name = ''; public function __construct($name){ $this->name = $name; } public function __toString() { return $this->name . ' has been zapped'; } } $person = new Person('fred'); print $person; // fred has been zapped 

And you get the expected result:

 fred has been zapped 
+3
source

Source: https://habr.com/ru/post/1303681/


All Articles