2016-07-09 174 views
-1

我有一个辅助类是这样的:解析错误:语法错误,意外“(”

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']; 
     }   
    } 
} 

而且它给我:

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

回答

1

你的问题是,你正试图定义因为你从来没有实例化类(静态),你正在调用一个静态变量,你不能调用一个自我静态函数。

如果我复制粘贴你的代码并运行它与PHP 7它给其他错误:

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

解决您的问题,使用此:

<?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(); 
+0

由于它的工作,但我要问,如果我想使用常量,如: – gentle

+0

感谢@ P0lT10n它工作,但我想问,如果我想使用常量像:const APP_URLl; (){ public static function Init }它给出错误 – gentle

+0

它会给你错误,因为你正在声明一个常量。无法将其声明为常量。请记住标记我的答案为正确的 – matiaslauriti

相关问题