1

I am trying to wrap my head around the static keyword in PHP. Here I wrote a small piece of code where my person1 instance of Human can call a static method called sayRealname(). But when I try to call a public static variable it gives an error. What is the reason for that?

class Human{
    public static $age=34;
    public static $name='humpty dumpty';
    protected static $realname='al';

    public static function sayRealname(){
        echo self::$age;
    }
}

$person1=new Human();
echo $person1->name; // error
$person1->sayRealname(); // prints 34
hasumedic
  • 2,139
  • 12
  • 17
AL-zami
  • 8,902
  • 15
  • 71
  • 130

1 Answers1

0

When you're accessing static content, you need to use the static operator ::.

On the other hand, the arrow operator -> is meant to be used in an instance context, which belongs to the particular instance upon it's being called.

You can read more about this in this part of the documentation.

hasumedic
  • 2,139
  • 12
  • 17