Daniel Szigeti
Daniel Szigeti

Reputation: 1

Unexpected $var (T_VARIABLE)

I want to write an easy battle in php between two characters (classes). This is my code:

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;

But the terminal is throws: 'unexpected $hp (T_VARIABLE) in /home/szigeti/Desktop/sublime/Game/Gameboard/index.php on line 11'.

Upvotes: 0

Views: 1032

Answers (1)

Script47
Script47

Reputation: 14530

You are missing the variable scope in your class You,

Change,

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

to,

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

Also, when calling a class variable you need to refer to the object that is referring to it,

Change,

$player = new You;

echo $hp;

to,

$player = new You;

echo $player->hp;

Reading Material

Please read up on PHP OOP from the official documentation to prevent future mistakes.

PHP OOP

Upvotes: 5

Related Questions