2

I have a bit of php which has to generate a script. Part of it is pretty much static, but the data is generated on the fly. I had a similar problem in another language a time back and solved it using constant substitutes.

What I'm 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 yes, how would I implement it, and if no, what would be a suitable alternative?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
SBoss
  • 8,845
  • 7
  • 28
  • 44

3 Answers3

1

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

The docs says it:

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

A simple try give this:

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

With:

$ 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.

NoDataFound
  • 11,381
  • 33
  • 59
1

The replace takes place on strings, so it is accepted. However the error you are receiving is due to PHPs lack of constant expressions. Ie. you cannot write constant that uses another constant. The only accepted syntax is when the second constant equals the first one.

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

Maciej Sz
  • 11,151
  • 7
  • 40
  • 56
  • Why are all the best features in versions I can't use yet! Thanks anyway, if I could use it this would be what I'm looking for. – SBoss Aug 26 '14 at 08:45
1

In versions of PHP prior to 5.6 you cannot do this. The only way to build a constant from constituant parts in those versions of PHP is to use define(). I'd have to look it up 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're defined in terms of other constants.

define() vs const

Community
  • 1
  • 1
GordonM
  • 31,179
  • 15
  • 87
  • 129
  • Thanks. I'll have to re-read define() but if I recall you can access those constants without a class modifier, right? – SBoss Aug 26 '14 at 08:43