Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing class member variables with expressions (concatenated string) in PHP

Tags:

php

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

like image 296
Prembo Avatar asked Jan 19 '23 23:01

Prembo


1 Answers

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

like image 185
cwallenpoole Avatar answered Feb 08 '23 15:02

cwallenpoole