简体   繁体   中英

I cannot use IF-THEN-ELSE and $_SERVER variables in PHP class definition

class MY_CONFIG {
    if ( $_SERVER["SERVER_ADDR"] == "127.0.0.1" ) {
        var $default = array( 'foo' => 1, 'bar' => 2 );
    } else {
        var $default = array( 'foo' => 3, 'bar' => 4 );
    }
}

I am new to PHP. What's wrong with my code above?

The system keeps saying:

Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION in C:\wamp\www\test\class.php on line 4

Thanks.

-- Hin

vars in a class definition have to be static. if you need to apply logic to them, it should be in the constructor:

class MY_CONFIG {
    var $default = array('foo' => 3, 'bar' => 4);

    public function __construct() {
        if ( $_SERVER["SERVER_ADDR"] == "127.0.0.1" ) {
          $this->default = array( 'foo' => 1, 'bar' => 2 );
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM