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
6
  • Why would name be static? Commented Mar 16, 2016 at 20:31
  • it could be anything .. i call it name .. Commented Mar 16, 2016 at 20:33
  • FYI, if you just want to get it to work... echo $person1::$name; Commented Mar 16, 2016 at 20:41
  • ok thanks! but why i can access the static method using an arrow operator ? Commented Mar 16, 2016 at 20:46
  • Because that's not how the language is defined :) Commented Mar 16, 2016 at 20:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.