Using const to const

I have a little php that needs to generate a script. Some of it is pretty static, but the data is generated on the fly. I had a similar problem in another language and solved it using constant placeholders.

What I am trying to do:

interface IConstants {
    const SUBSTITUTE = '!substitute';
    const FULL_STRING = 'var data = "' . self::SUBSTITUTE . '";';
}

class Util {
    public static function replace($haystack, $needle, $replace) {
    // implementation
    }
}

class SampleClass {
    public function getScript() {
        $someData = $this->getData();
        return Util::replace(IConstants::FULL_STRING, IConstants::SUBSTITUTE, $someData);
    }

    public function getData() {
        // generate $someData
        return $someData;
    }
}

      

Is this design accepted for PHP? If so, how do I implement it, and if not, what is a suitable alternative?

+3


source to share


3 answers


In PHP versions prior to 5.6, you cannot do this. The only way to construct a constituent constant in these PHP versions is to use define (). I would have to check this to be sure, but I don't think you can use define () to define a class / interface constant.

As of PHP 5.6, you will be able to define constants like this, but only if they are defined in terms of other constants.



define () vs const

+1


source


This is not possible in PHP, at least in 5.4.4, unlike Java.

The docs says the following:

The value must be a constant expression, not (for example) a variable, property, mathematical result, or function call.

Simple try:



$ php -r 'const FOOBAR = "AF" . "A". "R"; '
PHP Parse error:  syntax error, unexpected '.', expecting ',' or ';' in Command line code on line 1

      

FROM

$ php --version
PHP 5.4.4-14+deb7u14 (cli) (built: Aug 21 2014 08:36:44) 
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies

      

For global constants, you can use define .

+2


source


The replacement happens on strings, so it is accepted. However, the error you are getting is due to the lack of constant PHP expressions. I.e. you cannot write a constant that uses another constant. The only accepted syntax is when the second constant is equal to the first.

This has changed, but only in the latest PHP 5.6 which is still unstable: http://php.net/manual/en/migration56.new-features.php#migration56.new-features.const-scalar-exprs

+2


source







All Articles