0

I have 2 classes, one extends the other:

class Human {
    const PERKS = 'none';
    public function __construct() {
        echo self::PERKS;
    }
}

class King extends Human {
    const PERKS = 'crown';
}

Ignore the silly example. However, no matter whom I initialize I get printed 'none'.

  1. How exactly does the constructor work?
  2. How can I get around this?

Thank you.

1

1 Answer 1

4

self always refers to exact class in which it's used. From the manual:

Static references to the current class like self:: or CLASS are resolved using the class in which the function belongs, as in where it was defined.

To work around this, you can use the static class resolution operator, which is resolved at runtime instead, e.g.

class Human {
    const PERKS = 'none';
    public function __construct() {
        echo static::PERKS;
    }
}

class King extends Human {
    const PERKS = 'crown';
}

new King;
// crown

new Human;
// none

See https://eval.in/959784

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

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.