It's time to ditch Medium for good! 🌈⚡️

Introducing Devblog by Hashnode. Blog on your domain for FREE. Highly customizable and optimized for developers.

Learn more

PHP allows access to non-static methods using ClassName:: But Why does it throw error when accessing non-static properties using ClassName::?

Class Names can access non-static methods but cannot access non-static properties



class BaseClass {
    public $x = 10;
    public function __construct() {
        echo "BaseClass constructor". "<br>";

class SubClass extends BaseClass {
    public function __construct() {
        echo "SubClass constructor" . "<br>";
        print parent::$x;

(new SubClass());


Run Code to see Result on your Browser

Write your answer…

3 answers

From what I've read, PHP 4 didn't have the static keyword in function declarations, but still allowed you to call a method using the :: static operator. It was kept for backward compatibility reasons in PHP 5 and up and in PHP 7+ is deprecated. I started with PHP 5.4, so never encountered this quirk. To me, it seems like a bug. But it is indeed a "feature".

AARGH! as a Novice I find this very confusing. I guess I've to stop tiring myself over this and consider it as " This is how it works in PHP ".
Your answer sounds logical, helpful indeed Thanks!

Reply to this…

Share your programming knowledge and learn from the best developers on Hashnode

Get started

Statics are STATIC, they exist all the time. NON-STATIC means they only exist after you "new' and assign said resultant object to a variable, and will only exist on that variable. They never actually exist in memory on the class.

That's kind of the POINT of static and non-static... so if you're asking this you kind-of missed the point.

Show all replies

I think out of all the answers here yours make most sense to me. I think I now understand the why behind it. Thank you very much. 😊

Reply to this…

It does not make sense to access non-static things by class name, unless you also provide an instance somehow.

Non-static things exist individually for each object. E.g. MY car is red, not ALL cars, not just ANY car, but mine.

If you only use Car (the type) without any reference to the specific car, you have not unambiguously specified what you actually want.

For your case, I am not quite sure I understand, and I've not done PHP for years, but maybe the answer is that constructors are always static.

Which makes sense, since you're making a specific object. If it weren't static, you would need an object to create itself.

Show all replies

That's ok, hope the other answers explain the missing details

Reply to this…