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…

Hashnode is a friendly and inclusive dev community.
Come jump on the bandwagon!

  • 💬 Ask programming questions without being judged

  • 🧠 Stay in the loop and grow your knowledge

  • 🍕 More than 500K developers share programming wisdom here

  • ❤️ Support the growing dev community!

Create my profile

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…

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…

Mohammad Daud Ibrahim's photo

Mohammad Daud Ibrahim


The Measure of a Man is What He Does with Power.


Dhaka, Bangladesh.

Welcome to Hashnode
the dev community

The programming forum to discuss topics broader than bugs and issues, write and share knowledge and connect with the best developers.