[英]PHP - why I couldn't declare static const variable?
我會用它們來實現factory
模式,例如:
class Types{
static const car = "CarClass";
static const tree = "TreeClass";
static const cat = "CatClass";
static const deathstar = "DeathStarClass";
}
我想用它們像:
$x = new Types::car;
可能嗎?
如果我的班級在construcor中有參數,那該怎么辦呢:
$x = new Types::car(123);
你的代碼應該是:
class Types{
const car = "CarClass";
const tree = "TreeClass";
const cat = "CatClass";
const deathstar = "DeathStarClass";
}
請注意,由於常量與類定義相關聯,因此根據定義它們是靜態的。
來自Docs:
從PHP 5.3.0開始,可以使用變量引用該類。 變量的值不能是關鍵字(例如self,parent和static)。
http://www.php.net/manual/en/language.oop5.static.php
更多信息:
常量已經是靜態的,因為它們不依賴於類的實例。 以下是如何定義它們並根據需要使用它們:
class Types{
const car = "CarClass";
const tree = "TreeClass";
const cat = "CatClass";
const deathstar = "DeathStarClass";
}
$x = Types::car;
這是一個常數。 你無法改變它。 所以你有一個非靜態常量成員沒有任何意義。 因此,您不必將它們聲明為靜態或類變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.