2016-07-09 216 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

相關問題