日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php常量定义表达式,从表达式创建PHP类常量的最佳解决方法?

發布時間:2025/4/5 php 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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类常量的最佳解决方法?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。