-1

I have an helper class like this:

class Helper{   

    public static $app_url = self::getServerUrl();
    /**
    * Gets server url path
    */
    public static function getServerUrl(){
        global $cfg; // get variable cfg as global variable from config.php Modified by Gentle

        $port = $_SERVER['SERVER_PORT'];
        $http = "http";

        if($port == "80"){
          $port = "";  
        }

        if(!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on"){
           $http = "https";
        }
        if(empty($port)){
           return $http."://".$_SERVER['SERVER_NAME']."/".$cfg['afn'];
        }else{
           return $http."://".$_SERVER['SERVER_NAME'].":".$port."/".$cfg['afn']; 
        }        
    }
}

And its given me:

Parse error: syntax error, unexpected '(' on the line with public static $app_url = self::getServerUrl();

chris85
  • 23,846
  • 7
  • 34
  • 51
gentle
  • 15
  • 7

1 Answers1

1

Your problem is that you are trying to define an static variable with self static function. Since you have never instantiated the class (static) and you are calling an static variable, you cannot call a self static function.

If I copy paste your code and run it with PHP 7 it gives other error:

Fatal error: Constant expression contains invalid operations in C:\inetpub\wwwroot\test.php on line 4

To solve your problem, use this:

<?php
class Helper {   

    public static $app_url;

    public static function Init() {
        self::$app_url = self::getServerUrl();
    }

    public static function getServerUrl(){

        global $cfg; // get variable cfg as global variable from config.php Modified by Gentle

        $port = $_SERVER['SERVER_PORT'];
        $http = "http";

        if($port == "80"){
          $port = "";  
        }

        if(!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on"){
           $http = "https";
        }
        if(empty($port)){
           return $http."://".$_SERVER['SERVER_NAME']."/".$cfg['afn'];
        }else{
           return $http."://".$_SERVER['SERVER_NAME'].":".$port."/".$cfg['afn']; 
        }

    }

}
Helper::Init();
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
  • Thanks it worked, but I want to ask, if i want to use constant like: – gentle Jul 10 '16 at 02:19
  • Thanks @P0lT10n It worked but I want to ask if i want to use constant like: const APP_URLl; public static function Init() { self::APP_URL = self::getServerUrl(); } it gives error – gentle Jul 10 '16 at 02:25
  • It will give you error, because you are declaring a constant. There is no way to declare it as a constant. Remember to mark my answer as correct please – matiaslauriti Jul 10 '16 at 02:37