2013-04-12 23 views
0
class Constants 
{ 
     public static $url1  = "http=//url1"; 
     public static $url2  = Constants::$url1."/abc2"; 
     public static $url3  = Constants::$url1."/abc3"; 
     public static $url4  = Constants::$url1."/abc4"; 
} 

我知道這是不可能的常量VAR

所以我應該使用它喜歡有$ URL1認定中的在一個地方

class urlOnly 
{ 
     public static $url1  = "http=//url1"; 
} 
class Constants 
{ 
     public static $url1  = urlOnly::$url1; 
     public static $url2  = urlOnly::$url1."/abc2"; 
     public static $url3  = urlOnly::$url1."/abc3"; 
     public static $url4  = urlOnly::$url1."/abc4"; 
} 

另外,如果我想使用像這個,我可以確保類「urlOnly」只能被類「常量」訪問。

備用解決方案是最受歡迎的,因爲在這個解決方案中我需要創建兩個類。 此外,我只想和無法訪問的變量作爲變量的函數,我想這就像你可以做,以實現你在找什麼靜態

+0

這並不解決您最實際的問題。 '公共靜態$ foo = self :: $ bar'工作得很好;你不能*在'static'聲明中連接*東西。 – deceze

+0

正如我告訴我不想創建對象或調用一個fucntion,所以它不重複 –

+0

然後我不知道你在問什麼。你不能像你那樣動態地聲明類常量。鏈接的dupe顯示一個解決方法。拿它或問一個不同的問題。 – deceze

回答

1

您不能在類定義中使用非標量值。 改爲使用define()

+0

您*可以*使用「非標量」值(例如'array(...)'),你不能使用*非靜態*值。 – deceze

+0

謝謝。我會檢查。 '<?php class a {public $ a = array('a'=> 1 + 2); }?>'仍然導致錯誤。但是'<?php class a {public $ a = array(1); ''工作正常。所以表達是不允許的,對嗎? – BlitZ

+0

確切地說,*非靜態*值(即任何需要執行和計算的值)都不起作用。 – deceze

0

一件事來訪問是這樣的:

class Constants { 
    public static $url1 = "http://url1"; 
    public static $url2 = ""; 
    // etc 
} 

Constants::$url2 = Constants::$url1 . "/abc2"; 

不幸的是,爲了動態定義靜態值,你必須在類的上下文之外這麼做,因爲靜態變量只能用文字或變量初始化(因此爲什麼此答案的前一版本有解析錯誤)。

但是,我建議使用define,因爲它的目的是定義常量值,並且沒有理由將常量存儲在類的上下文中,除非它絕對有意義(至少在我看來)。

喜歡的東西:

define("URL1", "http:://url1"); 
define("URL2", URL1 . "/abc2"); 

那麼你也沒必要指定一個類存取,只需使用URL1URL2需要。

+1

爲什麼這是被投票下來? –

+1

我同意它不應該被投票下來.....但它給錯誤 解析錯誤:語法錯誤,意外的'。',期待','或';' –

+0

而這是^被否決的原因。 – deceze

0

通常沒有辦法在不調用類方法的情況下聲明動態常量和靜態屬性。但是你可以實現你想要的邏輯。 您應該在strirngs常量中使用佔位符。然後你應該添加靜態方法「get」來檢索常量並替換佔位符。就像這樣:

class Constants 
{ 
    protected static $config = array(
     'url1' => 'http=//url1', 
     'url2' => '%url1%/abc2', 
     'url3' => '%url1%/abc3', 
     'url4' => '%url1%/abc4', 
    ); 

    public static function get($name, $default = null) 
    { 
     if (!empty(self::$config[$name]) && is_string(self::$config[$name]) && preg_match('/%(\w[\w\d]+)%/', self::$config[$name], $matches)) { 
      self::$config[$name] = str_replace($matches[0], self::$config[$matches[1]], self::$config[$name]); 
     } 
     return self::$config[$name]; 
    } 
} 

如何使用:

Constants::get('url1'); 
Constants::get('url2'); 
Constants::get('url3'); 
Constants::get('url4');