views:

33

answers:

2

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

+3  A: 

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.

Owen
+2  A: 

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
Pascal MARTIN