2017-08-29 74 views
0

我想在两个字符(类)之间编写一个简单的PHP战斗。这是我的代码:

class Characters 
{ 
    public $hp = rand(int,int); 
    public $attack = rand(int,int); 
}; 

class You extends Characters 
{ 
    $hp = rand(10,20); //this is line 11 
    $attack = rand(2,10); 
}; 

$player = new You; 

echo $hp; 

但终端是抛出: '意外$马力的第11行(T_VARIABLE)在/home/szigeti/Desktop/sublime/Game/Gameboard/index.php'。

回答

5

你缺少你的类You变量范围,

变化,

class You extends Characters 
{ 
    $hp = rand(10,20); //this is line 11 
    $attack = rand(2,10); 
}; 

到,

class You extends Characters 
{ 
    public $hp = rand(10,20); //this is line 11 
    public $attack = rand(2,10); 
}; 

此外,调用类变量,当你需要参考是指它的对象,

更改,

$player = new You; 

echo $hp; 

到,

$player = new You; 

echo $player->hp; 

阅读材料

请PHP OOP从官方文档阅读,以防止未来的错误。

PHP OOP

+0

谢谢你这么多,如果 –

+0

@DanielSzigeti答案帮助,请接受它。 – Script47