4

I'm developing a class and I have this structure:

class userInfo {
    public $interval        = 60;
    public $av_langs        = null;

    public $ui_ip           = $_SERVER['REMOTE_ADDR'];
    public $ui_user_agent   = $_SERVER['HTTP_USER_AGENT'];

    public $ui_lang         = null;
    public $ui_country      = null;

    // non-relevant code removed
}

But when executing the script I get this error:

Parse error: syntax error, unexpected T_VARIABLE in D:\web\www\poll\get_user_info\get_user_info.php on line 12

When I changed the 2 $_SERVER vars to simple strings the error disappeared.

So what's the problem with $_SERVER in declaring class properties?

Thanks

Perception
  • 79,279
  • 19
  • 185
  • 195
medk
  • 9,233
  • 18
  • 57
  • 79
  • 4
    The above are not variable assignments, but class property *declarations*. As such they cannot hold expressions. Not allowed there. You must use constants or do it in the constructor. http://www.php.net/manual/en/language.oop5.properties.php – mario Aug 08 '11 at 12:26

3 Answers3

13

Use this code as a guide:

public function __construct() {
    $this->ui_ip = $_SERVER['REMOTE_ADDR'];
    $this->ui_user_agent = $_SERVER['HTTP_USER_AGENT'];
}
Perception
  • 79,279
  • 19
  • 185
  • 195
5

Property can be declared only with value, not expression.
You can create __construct() method, where you can initialize properties in any way.

OZ_
  • 12,492
  • 7
  • 50
  • 68
  • ok can you give me a simple example? I'm not very used to classes. – medk Aug 08 '11 at 12:30
  • I made simple set_ip() and get_ip() functions and put $ui->set_ip($_SERVER['REMOTE_ADDR']); $ui->get_ip(); and it works, but why not declaring it directly? – medk Aug 08 '11 at 12:35
  • 1
    @medk because `$_SERVER['REMOTE_ADDR']` is expression, and expressions are not allowed in that scope (because any expression can be fetched only in runtime). __construct() is "magic" method, where you can initialize all your properties in any way. [Read more in manual](http://php.net/manual/en/language.oop5.decon.php) – OZ_ Aug 08 '11 at 12:51
3

So what's the problem with $_SERVER in declaring class properties?

You can't preset class properties with variables nor with function calls.

Here is some in-depth discussion on why: Why don't PHP attributes allow functions?

The bottom line however is, it's simply not possible.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088