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

1
  • 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. php.net/manual/en/language.oop5.properties.php Commented Aug 8, 2011 at 12:26

3 Answers 3

13

Use this code as a guide:

public function __construct() {
    $this->ui_ip = $_SERVER['REMOTE_ADDR'];
    $this->ui_user_agent = $_SERVER['HTTP_USER_AGENT'];
}
Sign up to request clarification or add additional context in comments.

Comments

5

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

3 Comments

ok can you give me a simple example? I'm not very used to classes.
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 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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.