Access a variable declared in a class in PHP


I have a simple doubt about PHP. I have the following code in a file called gato.php:

class Animal{
    public $foodLevel=5;
class Cat extends Animal{

Then I have another file in which I have:

include_once "gato.php";
$susi = new Cat();
echo $susi->$foodLevel;

And I get the following errors:


Undefined variable: foodLevel


Can not access empty property

How could I access the variable foodLevel from the second file?

asked by kalia 29.07.2017 в 20:17

1 answer


You are trying to access the property as if its name were stored in a variable, the way you are looking for is:

echo  $susi->foodLevel;

What you try to do would work if it were something like this:

$myVar = 'foodLevel';

echo $susi->$myVar;
answered by 29.07.2017 / 20:21