class Hero
{
private $name;
private $weapon;
public function __construct( $name )
{
if (!is_string($name)) {
return false;
}
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function hasWeapon()
{
return !empty($this->weapon);
}
public function &getWeapon()
{
if (!$this->hasWeapon()) {
$retVal = false;
return $retVal;
}
return $this->weapon;
}
public function setWeapon( &$weapon )
{
if (!is_object($weapon) || get_class($weapon)!='Weapon') {
return false;
}
$this->weapon = $weapon;
return true;
}
public function __toString()
{
return $this->getName();
}
}
class Weapon
{
private $name;
public function __construct( $name )
{
if (!is_string($name)) {
return false;
}
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function __toString()
{
return $this->getName();
}
}
$held = new Hero('Brutus');
if (!$held->hasWeapon()) {
echo "{$held} ist unbewaffnet.";
}
if ($held->setWeapon(new Weapon('Schwert'))) {
echo "{$held} trägt nun die Waffe {$held->getWeapon()}.";
}