0

I have a project running on PHP 5.3.21 that I am trying to migrate to PHP 7.0. The project uses a lot the structure as in the example below:

<?php
class foo {
    protected $_const = self::MYCONST;
}

class boo extends foo {
    const MYCONST = "test";

    public function __construct() {
        echo $this->_const.PHP_EOL;
    }
}
new boo();

The expected result is printing "test", and it works perfectly on 5.3, but on 7.0 I get

PHP Fatal error: Uncaught Error: Undefined class constant 'self::MYCONST'

Any help will be highly appreciated

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Sherman
  • 36
  • 5
  • 3
    Just saying. Shouldn't the constant be defined in the parent class? – Rotimi Mar 24 '18 at 11:37
  • Can't even apply late static binding, as that is a run-time evaluation, and constant definitions can only be compile time – Mark Baker Mar 24 '18 at 11:42
  • The parent class has no knowledge (nor should it have) about anything defined in the child class. – M. Eriksson Mar 24 '18 at 11:43
  • I was almost sure this shoudn't work, but it does :P http://sandbox.onlinephpfunctions.com/code/43462e3581f9778e0bce57d1351ee9aa32f51e90 – mleko Mar 24 '18 at 11:44
  • @mleko - I think we have different definitions of "working" :-) That link produces: _"Fatal error: Uncaught Error: Undefined class constant 'self::MYCONST' in ..."_ – M. Eriksson Mar 24 '18 at 11:45
  • You need to set `$this->_const` in the `boo` constructor, because only `boo` knows that `foo` exists; `foo` doesn't know about `boo` – Mark Baker Mar 24 '18 at 11:45
  • @MagnusEriksson run this on 5.3, check link I provided – mleko Mar 24 '18 at 11:46
  • Funny enough it works on 5.3.. Weird – Rotimi Mar 24 '18 at 11:47
  • 1
    @mleko - Ah. Wow, then it works. I guess what we can take from that is that PHP has become more structured and "correct" lately :-) – M. Eriksson Mar 24 '18 at 11:47

1 Answers1

1

Try to transfer the constants to the parent classes in your project