php常量定义表达式,从表达式创建PHP类常量的最佳解决方法?
我希望能夠做到這樣的事情:
class Circle {
const RADIUS_TO_CIRCUMFERENCE = M_PI * 2; // Not allowed
private $radius;
public function __construct( $radius ) {
$this->radius = $radius;
}
...
public function getCircumference() {
return $this->radius * self::RADIUS_TO_CIRCUMFERENCE;
}
}
但我不能從這樣的表達式創建一個class constant:
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
所以我的問題是:這種PHP限制的最佳解決方法是什么?我知道以下變通方法,但還有其他更好的方法嗎?
1.創建一個屬性
class Circle {
private static $RADIUS_TO_CIRCUMFERENCE;
private $radius;
public function __construct( $radius ) {
$this->radius = $radius;
$this->RADIUS_TO_CIRCUMFERENCE = M_PI * 2;
}
...
public function getCircumference() {
return $this->radius * $this->RADIUS_TO_CIRCUMFERENCE;
}
}
我不喜歡這個,因為$RADIUS_TO_CIRCUMFERENCE的值可以改變,所以它不是真正的“常量”.
2.使用define()
define( 'RAD_TO_CIRCUM', M_PI * 2 );
class Circle {
const RADIUS_TO_CIRCUMFERENCE = RAD_TO_CIRCUM;
...
public function getCircumference() {
return $this->radius * self::RADIUS_TO_CIRCUMFERENCE;
}
}
這是更好的,因為該值確實是恒定的,但缺點是RAD_TO_CIRCUM已被全局定義.
一個題外話
我不明白這是如何工作的. (編輯:我測試了它,它確實有效.)根據Handbook of PHP Syntax:
The const modifier creates a compile-time constant and so the compiler will replace all usage of the constant with its value. In contrast, define creates a run-time constant which is not set until run-time. This is the reason why define constants may be assigned with expressional values, whereas const requires constant values which are known at compile-time.
手冊confirms“使用const關鍵字定義的常量…在編譯時定義”.
從3年前的this bug report開始,PHP團隊的一名成員寫道:
For the class constant we need a constant value at compile time and can’t evaluate expressions. define() is a regular function, evaluated at run time and can therefore contain any value of any form.
但在上面的示例中,RAD_TO_CIRCUM的值在編譯時是未知的.那么什么是編譯器為RADIUS_TO_CIRCUMFERENCE的值?
我猜測編譯器會為RADIUS_TO_CIRCUMFERENCE的值創建某種占位符,并且在運行時,該占位符將替換為RAD_TO_CIRCUM的值.這個占位符可能是resource的一種嗎?如果是這樣,也許應該避免這種技術?手冊says:“可以將常量定義為資源,但應該避免,因為它可能導致意外結果.”
3.創建一個方法
class Circle {
...
private static function RADIUS_TO_CIRCUMFERENCE() {
return M_PI * 2;
}
public function getCircumference() {
return $this->radius * $this->RADIUS_TO_CIRCUMFERENCE();
}
}
這是我最喜歡的解決方法,我知道.值是常量,不會影響全局空間.
還有其他解決方法甚至更好嗎?
總結
以上是生活随笔為你收集整理的php常量定义表达式,从表达式创建PHP类常量的最佳解决方法?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iis7.5php.2,Windows2
- 下一篇: php %3c php 攻击,web 攻