4

I'd like to initialize a class member var using an expression- by concatenating a string... Why is the following not possible...

class aClass {
    const COMPANY_NAME = "A Company";
    var $COPYRIGHT_TEXT = "Copyright © 2011 " . COMPANY_NAME;  // syntax error on this line - why?
    var $COPYRIGHT_TEXT2 = "Copyright © 2011 " . "A Company";   // even a syntax error on this line
}

Thanks very much for your help.

Prembo

Prembo
  • 2,256
  • 2
  • 30
  • 50

3 Answers3

5

Well, because that is how PHP works.

Variables which is initialized statically in PHP (anything outside of a method) may be assigned to static values, but they cannot be assigned to anything which requires a function call (other than array). you can get around this by placing the initializations in the constructor.

Additionally, you should be using either self::COMPANY_NAME or aClass::COMPANY_NAME, and var has been out of style since PHP 4. Use public/protected/private (and static where appropriate).

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
3

Because a value of the class property/constant can't be expression. Use constructor for these purposes.

public function __construct() {
    $this->COPYRIGHT_TEXT = "Copyright © 2011 " . self::COMPANY_NAME;
}
realmfoo
  • 433
  • 3
  • 11
1

FYI, gleaned from Static Function Variables and Concatenation in PHP you can also use define as in:

define('THING', 'foo' . 'bar');
class Thing {
    static $MyVar = THING;
}
Community
  • 1
  • 1
Neek
  • 7,181
  • 3
  • 37
  • 47