1

Sorry for the question but I don't understand how this works:

class Person {
    public static $age = 1;

    public function haveBirthday() {
        static::$age +=1;
    }
}

$joe = new Person;
$joe->haveBirthday();

echo Person::$age;

What I'm not understanding is this:

public function haveBirthday() {
    static::$age +=1;
}

Isn't supposed to return $age otherwise the value is lost? Why is it still working?

Thanks!

1
  • 1
    static mean created once and can be accessed with class name so now you can think of age created once and hence value Commented Sep 7, 2016 at 13:45

3 Answers 3

1

You've defined it as static, which means those are class level variables instead of instance level.

So when you call $joe->haveBirthday(); it updates the class level variable of the Person class which can accessed using Person::$age;.

Static variables does not need to be returned, you can access it directly from Class.

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

1 Comment

This was helpful. Thanks!
0

public static $age = 1; suggests this is a static property, which means this as a class property, not an instance's.

Comments

0

The method haveBirthday() does not return anything, it simply increase the static variable $age.

A static variable is shared by all instances of this classes. So it is not a good idea in your case, as all persons will have the same age.

class Person {
    public static $age = 1;

    public function haveBirthday() {
        static::$age +=1;
    }
}

$joe = new Person;
$jane = new Person;
$joe->haveBirthday();   // +1 => 2
$jane->haveBirthday();   // +1 => 3

echo Person::$age;  // Will return 3

Test it here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.