PHP Access child static properties from the parent classCreated by maxtingle on Sat 16th Jan 2016 in category Web Development. 1142 Views | Tags: php, oop, class, child, parent, propertiesRecently a co-worker of mine had a problem, he wanted to make a generic base class to reduce code duplication but he needed some variables, that would always be the same, from the child class.
He searched Google and StackOverflow a good amount for this issue but ultimately was unable to find anything on it and thus came to me. I, expecting it to be a basic access modifier issue, told him to make his variables protected static so it could be shared between the classes but that didn't work, the parent class just could not seem to see the child's declared variables.
I knew it was possible but couldn't remember how so I had a quick Google myself to make sure he hadn't missed anything but he hadn't, there really was no StackOverflow posts that described the solution to his problem without doing something hacky to work around the issue, such as having a constructor which sets the variable or a method in the base class, but those are not real solutions.
The solution was quite simple actually, just like in any other language, you define it in the parent class with the same modifiers then you re-declare it in the child class and it will override it.
Of course you will have to use the static reference in the parent class rather than self as self acts like a base reference in the parent and will give you the property value as it was declared in the parent.
It should look something along the lines of this:
abstract class Fruit {
public static $name;
public static function getName() {
return static::$name;
}
}
class Apple extends Fruit {
public static $name = "Apple";
}
So now when you call Apple::getName();
you will get "Apple". Pretty simple and to be expected really, just strange that it wasn't on StackOverflow or the Google search results.