Jmoon.C Jmoon.C - 3 months ago 8
PHP Question

When do we return values in PHP functions?

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!

Answer

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.