I have declared the beats function and am trying to use it. What is the difference between var_dump(is_a($sci, 'Scissors'))
and var_dump($roc->beats($sci))
? When I run this code the first var_dump returns true and the second false. I want both to return true.
abstract Class Option
{
private $beats;
public function beats($opponentsChoice)
{
return is_a($opponentsChoice, $this->beats);
}
}
Class Rock extends Option
{
private $beats = 'Scissors';
}
Class Paper extends Option
{
private $beats = 'Rock';
}
Class Scissors extends Option
{
private $beats = 'Paper';
}
$roc = new Rock;
$pap = new Paper;
$sci = new Scissors;
var_dump(is_a($sci, 'Scissors'));
var_dump($roc->beats($sci));
The problem is your private
variables.
private
variables are scoped only to the class they are defined in. Option::$beats
is a different variable than Rock::$beats
.
If you change your variables to be protected
instead, that will work, since all members of a class hierarchy will share protected
variables (and methods).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.