4

There's an open book quiz for a job application I'm doing, and it's obviously highlighted a shortcoming in my php knowledge.

Note, I'm not asking for the answer directly, I'm asking to be shown what I'm misunderstanding/lacking in how to answer it. The question is:

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's some way of adding exception handling to the class (though I would have thought 'print' would be the thing throwing the exception, or I'm just misunderstanding the question. I do know (from a quick test) that putting the print in a try..catch still causes the program to fail with a "catchable fatal error" (my catch did not fire).

What should I be reading up on ?

David

1
  • Trying not to answer your question; instead, in an attempt to give you a hint: Where in the question (#3) are exceptions mentioned? What made you feel you needed to use try...catch? Commented Mar 10, 2010 at 15:42

2 Answers 2

4

Hmm, sounds more like they're looking for your knowledge of PHP5 classes. I'd suggest taking a look at PHP's magic methods for more insight into how to accomplish what you're trying to do.

Basically, you're looking to have a printable representation of the object in question.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Here, you'd have to modify the class, to add the definition of that __toString method, that will return the name, and the "has been zapped" portion of string :

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 output :

fred has been zapped

Comments

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.