意外的$ var(T_VARIABLE)

时间:2017-08-29 09:12:41

标签: php

我想在两个角色(类)之间用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行的/home/szigeti/Desktop/sublime/Game/Gameboard/index.php中出现意外的$ hp(T_VARIABLE)。

1 个答案:

答案 0 :(得分: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