1 關注者

類別 yii\i18n\Formatter

繼承關係yii\i18n\Formatter » yii\base\Component » yii\base\BaseObject
實作yii\base\Configurable
版本可用性2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/i18n/Formatter.php

Formatter 提供了一組常用的資料格式化方法。

Formatter 提供的格式化方法都以 asXyz() 的形式命名。它們中一些方法的行為可以通過 Formatter 的屬性來配置。例如,通過配置 $dateFormat,可以控制 asDate() 如何將值格式化為日期字串。

Formatter 預設被配置為 yii\base\Application 中的應用程式元件。你可以通過 Yii::$app->formatter 訪問該實例。

Formatter 類別旨在根據 $locale 格式化數值。為了使此功能正常運作,必須安裝 PHP intl 擴展。但是,即使未安裝 PHP intl 擴展,大多數方法也能通過提供後備實作來運作。如果沒有 intl,月份和日期名稱僅以英文顯示。請注意,即使安裝了 intl 擴展,在 32 位系統上格式化年份 >=2038 或 <=1901 的日期和時間值仍將回退到 PHP 實作,因為 intl 在內部使用 32 位 UNIX 時間戳。在 64 位系統上,如果安裝了 intl 格式器,則在所有情況下都會使用它。

注意: Formatter 類別旨在用於格式化數值以顯示給不同語言和時區的使用者。如果您需要以機器可讀的格式格式化日期或時間,請改用 PHP date() 函數。

公共屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$baseUnits array 用作 $measureUnits 中最小可能單位的乘數的基礎單位。 yii\i18n\Formatter
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$booleanFormat array 格式化布林值時要顯示的文字。 yii\i18n\Formatter
$calendar IntlCalendar|integer|null 用於日期格式化的日曆。 yii\i18n\Formatter
$currencyCode string|null 3 字母 ISO 4217 貨幣代碼,指示用於 asCurrency() 的預設貨幣。 yii\i18n\Formatter
$currencyDecimalSeparator string|null 格式化貨幣時顯示為小數點的字元。 yii\i18n\Formatter
$dateFormat string 用於格式化日期的預設格式字串。 yii\i18n\Formatter
$datetimeFormat string 用於格式化日期和時間的預設格式字串。 yii\i18n\Formatter
$decimalSeparator string|null 格式化數字時顯示為小數點的字元。 yii\i18n\Formatter
$defaultTimeZone string 如果輸入值未明確包含時區,則假定的時區。 yii\i18n\Formatter
$language string|null 用於翻譯內部訊息的語言代碼(例如 en-USen)。 yii\i18n\Formatter
$locale string|null 用於本地化日期和數字格式的地區設定 ID。 yii\i18n\Formatter
$measureUnits array 重量和長度測量單位的配置。 yii\i18n\Formatter
$nullDisplay string|null 格式化 null 值時要顯示的文字。 yii\i18n\Formatter
$numberFormatterOptions array 傳遞到 intl NumberFormatter::setAttribute() 方法的所有數字格式器物件的名稱值對列表,這些物件由 createNumberFormatter() 建立。 yii\i18n\Formatter
$numberFormatterSymbols array 傳遞至 intl NumberFormatter::setSymbol() 方法的名稱值組列表,適用於由 createNumberFormatter() 建立的所有數字格式器物件。 yii\i18n\Formatter
$numberFormatterTextOptions array 傳遞至 intl NumberFormatter::setTextAttribute() 方法的名稱值組列表,適用於由 createNumberFormatter() 建立的所有數字格式器物件。 yii\i18n\Formatter
$sizeFormatBase integer 計算千位元組的基底(每千位元組 1000 或 1024 位元組),由 asSize()asShortSize() 使用。 yii\i18n\Formatter
$systemOfUnits string 預設度量衡系統。 yii\i18n\Formatter
$thousandSeparator string|null 格式化數字時顯示為千位分隔符號(也稱為分組分隔符號)的字元。 yii\i18n\Formatter
$timeFormat string 用於格式化 time 的預設格式字串。 yii\i18n\Formatter
$timeZone string|null 用於格式化時間和日期值的時區。 yii\i18n\Formatter

公共方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫非類別方法的具名方法。 yii\base\Component
__clone() 在透過複製現有物件建立物件後,會呼叫此方法。 yii\base\Component
__construct() 建構子。 yii\base\BaseObject
__get() 傳回元件屬性的值。 yii\base\Component
__isset() 檢查屬性是否已設定,即已定義且非 null。 yii\base\Component
__set() 設定元件屬性的值。 yii\base\Component
__unset() 將元件屬性設定為 null。 yii\base\Component
asBoolean() 將值格式化為布林值。 yii\i18n\Formatter
asCurrency() 將值格式化為貨幣數字。 yii\i18n\Formatter
asDate() 將值格式化為日期。 yii\i18n\Formatter
asDatetime() 將值格式化為日期時間。 yii\i18n\Formatter
asDecimal() 將值格式化為十進制數字。 yii\i18n\Formatter
asDuration() 以人類可讀的格式表示值的持續時間。 yii\i18n\Formatter
asEmail() 將值格式化為 mailto 連結。 yii\i18n\Formatter
asHtml() 將值格式化為 HTML 文字。 yii\i18n\Formatter
asImage() 將值格式化為圖片標籤。 yii\i18n\Formatter
asInteger() 將值格式化為整數數字,移除任何小數位數而不四捨五入。 yii\i18n\Formatter
asLength() 以人類可讀的形式格式化值長度,例如 12 meters yii\i18n\Formatter
asNtext() 將值格式化為 HTML 編碼的純文字,並將換行符號轉換為換行符。 yii\i18n\Formatter
asOrdinal() 將值格式化為數字的序數值。 yii\i18n\Formatter
asParagraphs() 將值格式化為 HTML 編碼的文字段落。 yii\i18n\Formatter
asPercent() 將值格式化為帶有 "%" 符號的百分比數字。 yii\i18n\Formatter
asRaw() 按原樣格式化值,不進行任何格式化。 yii\i18n\Formatter
asRelativeTime() 以人類可讀的形式格式化值為日期與現在之間的時間間隔。 yii\i18n\Formatter
asScientific() 將值格式化為科學記號數字。 yii\i18n\Formatter
asShortLength() 以人類可讀的形式格式化值長度,例如 12 m yii\i18n\Formatter
asShortSize() 以人類可讀的形式將位元組值格式化為大小,例如 12 kB yii\i18n\Formatter
asShortWeight() 以人類可讀的形式格式化值重量,例如 12 kg yii\i18n\Formatter
asSize() 以人類可讀的形式將位元組值格式化為大小,例如 12 kilobytes yii\i18n\Formatter
asSpellout() 將值格式化為數字拼字。 yii\i18n\Formatter
asText() 將值格式化為 HTML 編碼的純文字。 yii\i18n\Formatter
asTime() 將值格式化為時間。 yii\i18n\Formatter
asTimestamp() 將浮點數格式的日期、時間或日期時間格式化為 UNIX 時間戳記(自 1970-01-01 以來的秒數)。 yii\i18n\Formatter
asUrl() 將值格式化為超連結。 yii\i18n\Formatter
asWeight() 以人類可讀的形式格式化值重量,例如 12 kilograms yii\i18n\Formatter
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
behaviors() 傳回此元件應表現為的行為列表。 yii\base\Component
canGetProperty() 傳回指示是否可讀取屬性的值。 yii\base\Component
canSetProperty() 傳回指示是否可設定屬性的值。 yii\base\Component
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
detachBehavior() 從元件分離行為。 yii\base\Component
detachBehaviors() 從元件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
format() 根據給定的格式類型格式化值。 yii\i18n\Formatter
getBehavior() 傳回具名行為物件。 yii\base\Component
getBehaviors() 傳回附加到此元件的所有行為。 yii\base\Component
hasEventHandlers() 傳回指示是否有名稱事件附加任何處理常式的數值。 yii\base\Component
hasMethod() 傳回指示是否已定義方法的數值。 yii\base\Component
hasProperty() 傳回指示是否為此元件定義屬性的數值。 yii\base\Component
init() 初始化物件。 yii\i18n\Formatter
off() 從此元件分離現有的事件處理常式。 yii\base\Component
on() 將事件處理常式附加到事件。 yii\base\Component
trigger() 觸發事件。 yii\base\Component

受保護的方法

隱藏繼承的方法

方法 描述 定義於
asCurrencyStringFallback() 將值格式化為貨幣數字的回退。 yii\i18n\Formatter
asDecimalStringFallback() 將值格式化為十進制數字的回退。 yii\i18n\Formatter
asIntegerStringFallback() 將值格式化為整數數字的回退,移除任何小數位數而不四捨五入。 yii\i18n\Formatter
asPercentStringFallback() 將值格式化為帶有 "%" 符號的百分比數字的回退。 yii\i18n\Formatter
createNumberFormatter() 根據給定的類型和格式建立數字格式器。 yii\i18n\Formatter
formatNumber() 給定位元組值,格式化人類可讀形式的數字部分。 yii\i18n\Formatter
isNormalizedValueMispresented() 檢查給定值及其標準化版本的字串表示是否不同。 yii\i18n\Formatter
normalizeDatetimeValue() 將給定的日期時間值標準化為 DateTime 物件,供各種日期/時間格式化方法使用。 yii\i18n\Formatter
normalizeNumericStringValue() 標準化數值字串值。 yii\i18n\Formatter
normalizeNumericValue() 標準化數值輸入值。 yii\i18n\Formatter

常數

隱藏繼承的常數

常數 描述 定義於
FORMAT_WIDTH_LONG 'long' yii\i18n\Formatter
FORMAT_WIDTH_SHORT 'short' yii\i18n\Formatter
UNIT_LENGTH 'length' yii\i18n\Formatter
UNIT_SYSTEM_IMPERIAL 'imperial' yii\i18n\Formatter
UNIT_SYSTEM_METRIC 'metric' yii\i18n\Formatter
UNIT_WEIGHT 'mass' yii\i18n\Formatter

屬性詳細資訊

隱藏繼承的屬性

$baseUnits 公共屬性(自版本 2.0.13 起可用)

用作 $measureUnits 中最小可能單位的乘數的基礎單位。

public array $baseUnits = [
    
self::UNIT_LENGTH => [
        
self::UNIT_SYSTEM_IMPERIAL => 12,
        
self::UNIT_SYSTEM_METRIC => 1000,
    ],
    
self::UNIT_WEIGHT => [
        
self::UNIT_SYSTEM_IMPERIAL => 7000,
        
self::UNIT_SYSTEM_METRIC => 1000,
    ],
]
$booleanFormat 公共屬性

格式化布林值時要顯示的文字。第一個元素對應於 false 顯示的文字,第二個元素對應於 true。預設為 ['No', 'Yes'],其中 YesNo 將根據 $locale 翻譯。

public array $booleanFormat null
$calendar 公共屬性(自版本 2.0.7 起可用)

用於日期格式化的日曆。此屬性的值將直接傳遞到 IntlDateFormatter 類別的建構子

預設為 null,表示將使用公曆。您也可以明確傳遞常數 \IntlDateFormatter::GREGORIAN 以使用公曆。

若要使用替代日曆,例如 Jalali 日曆,請將此屬性設定為 \IntlDateFormatter::TRADITIONAL。然後必須在 $locale 中指定日曆,例如波斯日曆的格式器配置將為

'formatter' => [
    'locale' => 'fa_IR@calendar=persian',
    'calendar' => \IntlDateFormatter::TRADITIONAL,
],

可在 ICU 手冊中找到可用的日曆名稱。

自 PHP 5.5 起,您也可以使用 IntlCalendar 類別的實例。請查看 PHP 手冊 以取得更多詳細資訊。

如果 PHP intl 擴充功能不可用,設定此屬性將不會有任何作用。

另請參閱

$currencyCode 公共屬性

3 個字母的 ISO 4217 貨幣代碼,指示用於 asCurrency() 的預設貨幣。如果未設定,將使用對應於 $locale 的貨幣代碼。請注意,在這種情況下,$locale 必須使用國家/地區代碼指定,例如 en-US,否則無法判斷預設貨幣。

public string|null $currencyCode null
$currencyDecimalSeparator 公共屬性(自版本 2.0.35 起可用)

格式化貨幣時顯示為小數點的字元。如果未設定,將使用對應於 $locale 的貨幣小數分隔符號。如果 PHP intl 擴充功能不可用,設定此屬性將不會有任何作用。

$dateFormat 公共屬性

用於格式化 date 的預設格式字串。這可以是 "short"、"medium"、"long" 或 "full",代表不同長度的預設格式。

它也可以是 ICU 手冊中指定的自訂格式。或者,這可以是帶有 php: 前綴的字串,代表 PHP date() 函數可辨識的格式。

例如

'MM/dd/yyyy' // date in ICU format
'php:m/d/Y' // the same date in PHP format
public string $dateFormat 'medium'
$datetimeFormat 公共屬性

用於格式化 date and time 的預設格式字串。這可以是 "short"、"medium"、"long" 或 "full",代表不同長度的預設格式。

它也可以是 ICU 手冊中指定的自訂格式。

或者,這可以是帶有 php: 前綴的字串,代表 PHP date() 函數可辨識的格式。

例如

'MM/dd/yyyy HH:mm:ss' // date and time in ICU format
'php:m/d/Y H:i:s' // the same date and time in PHP format
public string $datetimeFormat 'medium'
$decimalSeparator 公共屬性

格式化數字時顯示為小數點的字元。如果未設定,將使用對應於 $locale 的小數分隔符號。如果 PHP intl 擴充功能不可用,預設值為 '.'。

$defaultTimeZone 公共屬性(自版本 2.0.1 起可用)

如果輸入值未明確包含時區,則假定的時區。

該值必須是有效的時區識別碼,例如 UTCEurope/BerlinAmerica/Chicago。請參閱 php 手冊 以取得可用的時區。

預設為 UTC,因此您只需在資料庫中以另一個時區儲存日期時間值時調整此值。

請注意,UNIX 時間戳記根據其定義始終為 UTC。這表示指定與 UTC 不同的預設時區對以 UNIX 時間戳記形式給定的日期值沒有影響。

public string $defaultTimeZone 'UTC'
$language 公共屬性(自版本 2.0.28 起可用)

用於翻譯內部訊息的語言代碼(例如 en-USen)。如果未設定,將使用 $locale(如果包含 @calendar 參數,則不包含)。

public string|null $language null
$locale 公共屬性

用於本地化日期和數字格式的地區設定 ID。對於數字和日期格式,這僅在安裝 PHP intl 擴充功能時才有效。如果未設定,將使用 yii\base\Application::$language

public string|null $locale null
$measureUnits 公共屬性(自版本 2.0.13 起可用)

重量和長度度量單位的配置。此陣列包含最常用的度量單位,但您可以根據特殊需求變更它。

例如,您可以新增較小的度量單位

$this->measureUnits[self::UNIT_LENGTH][self::UNIT_SYSTEM_METRIC] = [
    'nanometer' => 0.000001
]

另請參閱

public array $measureUnits = [
    
self::UNIT_LENGTH => [
        
self::UNIT_SYSTEM_IMPERIAL => [
            
'inch' => 1,
            
'foot' => 12,
            
'yard' => 36,
            
'chain' => 792,
            
'furlong' => 7920,
            
'mile' => 63360,
        ],
        
self::UNIT_SYSTEM_METRIC => [
            
'millimeter' => 1,
            
'centimeter' => 10,
            
'meter' => 1000,
            
'kilometer' => 1000000,
        ],
    ],
    
self::UNIT_WEIGHT => [
        
self::UNIT_SYSTEM_IMPERIAL => [
            
'grain' => 1,
            
'drachm' => 27.34375,
            
'ounce' => 437.5,
            
'pound' => 7000,
            
'stone' => 98000,
            
'quarter' => 196000,
            
'hundredweight' => 784000,
            
'ton' => 15680000,
        ],
        
self::UNIT_SYSTEM_METRIC => [
            
'gram' => 1,
            
'kilogram' => 1000,
            
'ton' => 1000000,
        ],
    ],
]
$nullDisplay 公共屬性

格式化 null 值時要顯示的文字。預設為 '<span class="not-set">(not set)</span>',其中 (not set) 將根據 $locale 翻譯。

public string|null $nullDisplay null
$numberFormatterOptions public property

傳遞至 intl NumberFormatter::setAttribute() 方法的名稱值配對列表,適用於由 createNumberFormatter() 建立的所有數字格式器物件。 僅在安裝 PHP intl 擴充套件 時,此屬性才會生效。

有關可能的選項,請參閱 PHP 手冊

例如,若要調整小數位數的最大值和最小值,您可以像以下方式配置此屬性

[
    NumberFormatter::MIN_FRACTION_DIGITS => 0,
    NumberFormatter::MAX_FRACTION_DIGITS => 2,
]
$numberFormatterSymbols public property (available since version 2.0.4)

傳遞至 intl NumberFormatter::setSymbol() 方法的名稱值配對列表,適用於由 createNumberFormatter() 建立的所有數字格式器物件。 僅在安裝 PHP intl 擴充套件 時,此屬性才會生效。

有關可能的選項,請參閱 PHP 手冊

例如,若要選擇自訂貨幣符號,例如 U+20BD 而不是俄羅斯盧布的 руб.

[
    NumberFormatter::CURRENCY_SYMBOL => '₽',
]
$numberFormatterTextOptions public property

傳遞至 intl NumberFormatter::setTextAttribute() 方法的名稱值配對列表,適用於由 createNumberFormatter() 建立的所有數字格式器物件。 僅在安裝 PHP intl 擴充套件 時,此屬性才會生效。

有關可能的選項,請參閱 PHP 手冊

例如,若要變更負數的負號,您可以像以下方式配置此屬性

[
    NumberFormatter::NEGATIVE_PREFIX => 'MINUS',
]
$sizeFormatBase public property

計算千位元組的基數(每千位元組 1000 或 1024 位元組),由 asSize()asShortSize() 使用。預設值為 1024。

public integer $sizeFormatBase 1024
$systemOfUnits public property (available since version 2.0.13)

預設的度量單位系統。預設為 UNIT_SYSTEM_METRIC。可能的值

另請參閱

public string $systemOfUnits self::UNIT_SYSTEM_METRIC
$thousandSeparator public property

格式化數字時,顯示為千位分隔符號(也稱為分組分隔符號)的字元。 如果未設定,將使用對應於 $locale 的千位分隔符號。 如果 PHP intl 擴充套件 不可用,則預設值為 ','。

$timeFormat public property

用於格式化時間的預設格式字串。 這可以是 "short"、"medium"、"long" 或 "full",代表不同長度的預設格式。

它也可以是 ICU 手冊中指定的自訂格式。或者,這可以是帶有 php: 前綴的字串,代表 PHP date() 函數可辨識的格式。

例如

'HH:mm:ss' // time in ICU format
'php:H:i:s' // the same time in PHP format
public string $timeFormat 'medium'
$timeZone public property

用於格式化時間和日期值的時區。

這可以是任何可以傳遞給 date_default_timezone_set() 的值,例如 UTCEurope/BerlinAmerica/Chicago。 有關可用的時區,請參閱 php 手冊。 如果未設定此屬性,將使用 yii\base\Application::$timeZone

請注意,如果輸入日期值中未包含時區,則輸入資料的預設時區預設為 UTC。 如果您將資料以不同的時區儲存在資料庫中,則必須相應地調整 $defaultTimeZone

public string|null $timeZone null

方法詳情

隱藏繼承的方法

__call() public method

定義於: yii\base\Component::__call()

呼叫非類別方法的具名方法。

此方法將檢查是否有任何附加的行為具有指定的名稱方法,並在可用時執行它。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當調用未知方法時,它將被隱式呼叫。

public mixed __call ( $name, $params )
$name string

方法名稱

$params array

方法參數

return mixed

方法傳回值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() public method

定義於: yii\base\Component::__clone()

在透過複製現有物件建立物件後,會呼叫此方法。

它會移除所有行為,因為這些行為都附加到舊物件。

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() public method

定義於: yii\base\BaseObject::__construct()

建構子。

預設實作執行兩件事

  • 使用給定的配置 $config 初始化物件。
  • 呼叫 init()

如果在子類別中覆寫此方法,建議

  • 建構子的最後一個參數是配置陣列,例如此處的 $config
  • 在建構子結尾呼叫父類別實作。
public void __construct ( $config = [] )
$config array

將用於初始化物件屬性的名稱值配對

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

定義於: yii\base\Component::__get()

傳回元件屬性的值。

此方法將依以下順序檢查並相應地執行動作

  • getter 定義的屬性:傳回 getter 結果
  • 行為的屬性:傳回行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $component->property; 時,它將被隱式呼叫。

另請參閱 __set()

public mixed __get ( $name )
$name string

屬性名稱

return mixed

屬性值或行為的屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯寫。

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

定義於: yii\base\Component::__isset()

檢查屬性是否已設定,即已定義且非 null。

此方法將依以下順序檢查並相應地執行動作

  • setter 定義的屬性:傳回屬性是否已設定
  • 行為的屬性:傳回屬性是否已設定
  • 對於不存在的屬性傳回 false

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property) 時,它將被隱式呼叫。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

具名屬性是否已設定

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() public method

定義於: yii\base\Component::__set()

設定元件屬性的值。

此方法將依以下順序檢查並相應地執行動作

  • setter 定義的屬性:設定屬性值
  • 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
  • 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
  • 行為的屬性:設定行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value; 時,它將被隱式呼叫。

另請參閱 __get()

public void __set ( $name, $value )
$name string

屬性名稱或事件名稱

$value mixed

屬性值

throws yii\base\UnknownPropertyException

如果未定義屬性

throws yii\base\InvalidCallException

如果屬性為唯讀。

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__unset() public method

定義於: yii\base\Component::__unset()

將元件屬性設定為 null。

此方法將依以下順序檢查並相應地執行動作

  • setter 定義的屬性:將屬性值設定為 null
  • 行為的屬性:將屬性值設定為 null

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property) 時,它將被隱式呼叫。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

public void __unset ( $name )
$name string

屬性名稱

throws yii\base\InvalidCallException

如果屬性為唯讀。

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            
asBoolean() public method

將值格式化為布林值。

另請參閱 $booleanFormat

public string asBoolean ( $value )
$value mixed

要格式化的值。

return string

格式化後的結果。

                public function asBoolean($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
}

            
asCurrency() public method

將值格式化為貨幣數字。

此函數不要求安裝 PHP intl 擴充套件 才能運作,但強烈建議安裝它以獲得良好的格式化結果。

自 2.0.16 版起,正規化後呈現錯誤的數字會使用不支援 PHP intl 擴充套件的回退函數格式化為字串。 對於非常大的數字,建議將其作為字串傳遞,並且不要使用科學記號表示法,否則輸出可能不正確。

public string asCurrency ( $value, $currency null, $options = [], $textOptions = [] )
$value mixed

要格式化的值。

$currency string|null

指示要使用的貨幣的 3 個字母 ISO 4217 貨幣代碼。 如果為 null,將使用 $currencyCode

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

throws yii\base\InvalidConfigException

如果未給定貨幣且未定義 $currencyCode

                public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asCurrencyStringFallback((string) $value, $currency);
    }
    if ($this->_intlLoaded) {
        $currency = $currency ?: $this->currencyCode;
        // currency code must be set before fraction digits
        // https://php.dev.org.tw/manual/en/numberformatter.formatcurrency.php#114376
        if ($currency && !isset($textOptions[NumberFormatter::CURRENCY_CODE])) {
            $textOptions[NumberFormatter::CURRENCY_CODE] = $currency;
        }
        $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
        if ($currency === null) {
            $result = $formatter->format($normalizedValue);
        } else {
            $result = $formatter->formatCurrency($normalizedValue, $currency);
        }
        if ($result === false) {
            throw new InvalidArgumentException('Formatting currency value failed: ' . $formatter->getErrorCode() . ' ' . $formatter->getErrorMessage());
        }
        return $result;
    }
    if ($currency === null) {
        if ($this->currencyCode === null) {
            throw new InvalidConfigException('The default currency code for the formatter is not defined and the php intl extension is not installed which could take the default currency from the locale.');
        }
        $currency = $this->currencyCode;
    }
    return $currency . ' ' . $this->asDecimal($normalizedValue, 2, $options, $textOptions);
}

            
asCurrencyStringFallback() protected method (available since version 2.0.16)

將值格式化為貨幣數字的回退。

protected string asCurrencyStringFallback ( $value, $currency null )
$value string|integer|float

要格式化的值。

$currency string|null

指示要使用的貨幣的 3 個字母 ISO 4217 貨幣代碼。 如果為 null,將使用 $currencyCode

return string

格式化後的結果。

throws yii\base\InvalidConfigException

如果未給定貨幣且未定義 $currencyCode

                protected function asCurrencyStringFallback($value, $currency = null)
{
    if ($currency === null) {
        if ($this->currencyCode === null) {
            throw new InvalidConfigException('The default currency code for the formatter is not defined.');
        }
        $currency = $this->currencyCode;
    }
    return $currency . ' ' . $this->asDecimalStringFallback($value, 2);
}

            
asDate() public method

將值格式化為日期。

另請參閱 $dateFormat

public string asDate ( $value, $format null )
$value integer|string|DateTime|DateTimeInterface|null

要格式化的值。 支援以下值類型

  • 表示 UNIX 時間戳記的整數。 根據定義,UNIX 時間戳記始終為 UTC。
  • 可以 解析以建立 DateTime 物件 的字串。 時間戳記假定為 $defaultTimeZone,除非明確給定時區。
  • PHP DateTime 物件。 您可以為 DateTime 物件設定時區,以指定來源時區。

格式器將根據 $timeZone 轉換日期值,然後再進行格式化。 如果不應執行時區轉換,則需要將 $defaultTimeZone$timeZone 設定為相同的值。 此外,對於沒有時間資訊的值(例如 "2017-06-05")也不會執行轉換。

$format string|null

用於將值轉換為日期字串的格式。 如果為 null,將使用 $dateFormat

這可以是 "short"、"medium"、"long" 或 "full",代表不同長度的預設格式。 它也可以是在 ICU 手冊 中指定的自訂格式。

或者,這可以是帶有 php: 前綴的字串,表示 PHP date() 函數可以識別的格式。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值無法評估為日期值。

throws yii\base\InvalidConfigException

如果日期格式無效。

                public function asDate($value, $format = null)
{
    if ($format === null) {
        $format = $this->dateFormat;
    }
    return $this->formatDateTimeValue($value, $format, 'date');
}

            
asDatetime() public method

將值格式化為日期時間。

另請參閱 $datetimeFormat

public string asDatetime ( $value, $format null )
$value integer|string|DateTime|DateTimeInterface|null

要格式化的值。 支援以下值類型

  • 表示 UNIX 時間戳記的整數。 根據定義,UNIX 時間戳記始終為 UTC。
  • 可以 解析以建立 DateTime 物件 的字串。 時間戳記假定為 $defaultTimeZone,除非明確給定時區。
  • PHP DateTime 物件。 您可以為 DateTime 物件設定時區,以指定來源時區。

格式器將根據 $timeZone 轉換日期值,然後再進行格式化。 如果不應執行時區轉換,則需要將 $defaultTimeZone$timeZone 設定為相同的值。

$format string|null

用於將值轉換為日期字串的格式。 如果為 null,將使用 $datetimeFormat

這可以是 "short"、"medium"、"long" 或 "full",代表不同長度的預設格式。 它也可以是在 ICU 手冊 中指定的自訂格式。

或者,這可以是帶有 php: 前綴的字串,表示 PHP date() 函數可以識別的格式。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值無法評估為日期值。

throws yii\base\InvalidConfigException

如果日期格式無效。

                public function asDatetime($value, $format = null)
{
    if ($format === null) {
        $format = $this->datetimeFormat;
    }
    return $this->formatDateTimeValue($value, $format, 'datetime');
}

            
asDecimal() public method

將值格式化為十進制數字。

屬性 $decimalSeparator 將用於表示小數點。 該值會自動四捨五入到定義的小數位數。

自 2.0.16 版起,正規化後呈現錯誤的數字會使用不支援 PHP intl 擴充套件 的回退函數格式化為字串。 對於非常大的數字,建議將其作為字串傳遞,並且不要使用科學記號表示法,否則輸出可能不正確。

另請參閱

public string asDecimal ( $value, $decimals null, $options = [], $textOptions = [] )
$value mixed

要格式化的值。

$decimals integer|null

小數點後的位數。 如果未給定,則位數取決於輸入值,並根據 NumberFormatter::MIN_FRACTION_DIGITSNumberFormatter::MAX_FRACTION_DIGITS 確定,可以使用 $numberFormatterOptions 進行配置。 如果 PHP intl 擴充套件不可用,則預設值為 2。 如果您希望在使用 intl 和不使用 intl 的環境之間保持一致的行為,則應在此處明確指定一個值。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

                public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asDecimalStringFallback((string) $value, $decimals);
    }
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
        if (($result = $f->format($normalizedValue)) === false) {
            throw new InvalidArgumentException('Formatting decimal value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    if ($decimals === null) {
        $decimals = 2;
    }
    return number_format($normalizedValue, $decimals, $this->decimalSeparator, $this->thousandSeparator);
}

            
asDecimalStringFallback() protected method (available since version 2.0.16)

將值格式化為十進制數字的回退。

屬性 $decimalSeparator 將用於表示小數點。 該值會自動四捨五入到定義的小數位數。

另請參閱

protected string asDecimalStringFallback ( $value, $decimals 2 )
$value string|integer|float

要格式化的值。

$decimals integer|null

小數點後的位數。 預設值為 2

return string

格式化後的結果。

                protected function asDecimalStringFallback($value, $decimals = 2)
{
    if (empty($value)) {
        $value = 0;
    }
    $value = $this->normalizeNumericStringValue((string) $value);
    $separatorPosition = strrpos($value, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($value, 0, $separatorPosition);
        $fractionalPart = substr($value, $separatorPosition + 1);
    } else {
        $integerPart = $value;
        $fractionalPart = null;
    }
    $decimalOutput = '';
    if ($decimals === null) {
        $decimals = 2;
    }
    $carry = 0;
    if ($decimals > 0) {
        $decimalSeparator = $this->decimalSeparator;
        if ($this->decimalSeparator === null) {
            $decimalSeparator = '.';
        }
        if ($fractionalPart === null) {
            $fractionalPart = str_repeat('0', $decimals);
        } elseif (strlen($fractionalPart) > $decimals) {
            $cursor = $decimals;
            // checking if fractional part must be rounded
            if ((int) substr($fractionalPart, $cursor, 1) >= 5) {
                while (--$cursor >= 0) {
                    $carry = 0;
                    $oneUp = (int) substr($fractionalPart, $cursor, 1) + 1;
                    if ($oneUp === 10) {
                        $oneUp = 0;
                        $carry = 1;
                    }
                    $fractionalPart = substr($fractionalPart, 0, $cursor) . $oneUp . substr($fractionalPart, $cursor + 1);
                    if ($carry === 0) {
                        break;
                    }
                }
            }
            $fractionalPart = substr($fractionalPart, 0, $decimals);
        } elseif (strlen($fractionalPart) < $decimals) {
            $fractionalPart = str_pad($fractionalPart, $decimals, '0');
        }
        $decimalOutput .= $decimalSeparator . $fractionalPart;
    }
    // checking if integer part must be rounded
    if ($carry || ($decimals === 0 && $fractionalPart !== null && (int) substr($fractionalPart, 0, 1) >= 5)) {
        $integerPartLength = strlen($integerPart);
        $cursor = 0;
        while (++$cursor <= $integerPartLength) {
            $carry = 0;
            $oneUp = (int) substr($integerPart, -$cursor, 1) + 1;
            if ($oneUp === 10) {
                $oneUp = 0;
                $carry = 1;
            }
            $integerPart = substr($integerPart, 0, -$cursor) . $oneUp . substr($integerPart, $integerPartLength - $cursor + 1);
            if ($carry === 0) {
                break;
            }
        }
        if ($carry === 1) {
            $integerPart = '1' . $integerPart;
        }
    }
    if (strlen($integerPart) > 3) {
        $thousandSeparator = $this->thousandSeparator;
        if ($thousandSeparator === null) {
            $thousandSeparator = ',';
        }
        $integerPart = strrev(implode(',', str_split(strrev($integerPart), 3)));
        if ($thousandSeparator !== ',') {
            $integerPart = str_replace(',', $thousandSeparator, $integerPart);
        }
    }
    return $integerPart . $decimalOutput;
}

            
asDuration() public method (available since version 2.0.7)

以人類可讀的格式表示值的持續時間。

public string asDuration ( $value, $implodeString ', ', $negativeSign '-' )
$value DateInterval|string|integer|null

要格式化的值。 可接受的格式

  • DateInterval 物件
  • 整數 - 秒數。 例如:值 131 表示 2 分鐘,11 秒
  • ISO8601 持續時間格式。 例如,所有這些值都表示 1 天,2 小時,30 分鐘 的持續時間: 2015-01-01T13:00:00Z/2015-01-02T13:30:00Z - 兩個日期時間值之間 2015-01-01T13:00:00Z/P1D2H30M - 日期時間值之後的時間間隔 P1D2H30M/2015-01-02T13:30:00Z - 日期時間值之前的时间間隔 P1D2H30M - 僅僅是日期間隔 P-1D2H30M - 負日期間隔 (-1 天,2 小時,30 分鐘)
$implodeString string

將用於連接持續時間部分。 預設為 ,

$negativeSign string

當格式化的持續時間為負數時,將作為前綴。 預設為 -

return string

格式化的持續時間。

                public function asDuration($value, $implodeString = ', ', $negativeSign = '-')
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    if ($value instanceof DateInterval) {
        $isNegative = $value->invert;
        $interval = $value;
    } elseif (is_numeric($value)) {
        $isNegative = $value < 0;
        $zeroDateTime = (new DateTime())->setTimestamp(0);
        $valueDateTime = (new DateTime())->setTimestamp(abs($value));
        $interval = $valueDateTime->diff($zeroDateTime);
    } elseif (strncmp($value, 'P-', 2) === 0) {
        $interval = new DateInterval('P' . substr($value, 2));
        $isNegative = true;
    } else {
        $interval = new DateInterval($value);
        $isNegative = $interval->invert;
    }
    $parts = [];
    if ($interval->y > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 year} other{# years}}', ['delta' => $interval->y], $this->language);
    }
    if ($interval->m > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 month} other{# months}}', ['delta' => $interval->m], $this->language);
    }
    if ($interval->d > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 day} other{# days}}', ['delta' => $interval->d], $this->language);
    }
    if ($interval->h > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 hour} other{# hours}}', ['delta' => $interval->h], $this->language);
    }
    if ($interval->i > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 minute} other{# minutes}}', ['delta' => $interval->i], $this->language);
    }
    if ($interval->s > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 second} other{# seconds}}', ['delta' => $interval->s], $this->language);
    }
    if ($interval->s === 0 && empty($parts)) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 second} other{# seconds}}', ['delta' => $interval->s], $this->language);
        $isNegative = false;
    }
    return empty($parts) ? $this->nullDisplay : (($isNegative ? $negativeSign : '') . implode($implodeString, $parts));
}

            
asEmail() public method

將值格式化為 mailto 連結。

public string asEmail ( $value, $options = [] )
$value string|null

要格式化的值。

$options array

標籤選項以名稱-值配對的方式呈現。請參閱 yii\helpers\Html::mailto()

return string

格式化後的結果。

                public function asEmail($value, $options = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return Html::mailto(Html::encode($value), $value, $options);
}

            
asHtml() public method

將值格式化為 HTML 文字。

此值將使用 yii\helpers\HtmlPurifier 進行淨化,以避免 XSS 攻擊。如果您不希望對該值進行任何淨化,請使用 asRaw()

public string asHtml ( $value, $config null )
$value string|null

要格式化的值。

$config array|null

HTMLPurifier 類別的配置。

return string

格式化後的結果。

                public function asHtml($value, $config = null)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return HtmlPurifier::process($value, $config);
}

            
asImage() public method

將值格式化為圖片標籤。

public string asImage ( $value, $options = [] )
$value mixed

要格式化的值。

$options array

標籤選項以名稱-值配對的方式呈現。請參閱 yii\helpers\Html::img()

return string

格式化後的結果。

                public function asImage($value, $options = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return Html::img($value, $options);
}

            
asInteger() public method

將值格式化為整數數字,移除任何小數位數而不四捨五入。

自 2.0.16 版起,正規化後呈現錯誤的數字會使用不支援 PHP intl 擴充套件 的回退函數格式化為字串。 對於非常大的數字,建議將其作為字串傳遞,並且不要使用科學記號表示法,否則輸出可能不正確。

public string asInteger ( $value, $options = [], $textOptions = [] )
$value mixed

要格式化的值。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

                public function asInteger($value, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asIntegerStringFallback((string) $value);
    }
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
        $f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
        if (($result = $f->format($normalizedValue, NumberFormatter::TYPE_INT64)) === false) {
            throw new InvalidArgumentException('Formatting integer value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    return number_format((int) $normalizedValue, 0, $this->decimalSeparator, $this->thousandSeparator);
}

            
asIntegerStringFallback() protected method (available since version 2.0.16)

將值格式化為整數數字的回退,移除任何小數位數而不四捨五入。

protected string asIntegerStringFallback ( $value )
$value string|integer|float

要格式化的值。

return string

格式化後的結果。

                protected function asIntegerStringFallback($value)
{
    if (empty($value)) {
        $value = 0;
    }
    $value = $this->normalizeNumericStringValue((string) $value);
    $separatorPosition = strrpos($value, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($value, 0, $separatorPosition);
    } else {
        $integerPart = $value;
    }
    return $this->asDecimalStringFallback($integerPart, 0);
}

            
asLength() public method (available since version 2.0.13)

以人類可讀的形式格式化值長度,例如 12 meters

如果您需要將值的單位更改為最小單位的倍數,請檢查屬性 $baseUnits;如果您需要在 UNIT_SYSTEM_METRICUNIT_SYSTEM_IMPERIAL 之間切換,請檢查 $systemOfUnits

另請參閱 asLength()

public string asLength ( $value, $decimals null, $numberOptions = [], $textOptions = [] )
$value float|integer

要格式化的值。

$decimals integer|null

小數點後的位數。

$numberOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

throws yii\base\InvalidConfigException

當未安裝 INTL 或不包含所需資訊時。

                public function asLength($value, $decimals = null, $numberOptions = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_LENGTH, self::FORMAT_WIDTH_LONG, $value, $decimals, $numberOptions, $textOptions);
}

            
asNtext() public method

將值格式化為 HTML 編碼的純文字,並將換行符號轉換為換行符。

public string asNtext ( $value )
$value string|null

要格式化的值。

return string

格式化後的結果。

                public function asNtext($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return nl2br(Html::encode($value));
}

            
asOrdinal() public method

將值格式化為數字的序數值。

此函數需要安裝 PHP intl 擴充套件

此格式器不適用於非常大的數字。

public string asOrdinal ( $value )
$value mixed

要格式化的值

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

throws yii\base\InvalidConfigException

PHP intl 擴充套件 不可用時。

                public function asOrdinal($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $value = $this->normalizeNumericValue($value);
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::ORDINAL);
        if (($result = $f->format($value)) === false) {
            throw new InvalidArgumentException('Formatting number as ordinal failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
}

            
asParagraphs() public method

將值格式化為 HTML 編碼的文字段落。

每個文字段落都包含在 <p> 標籤內。一個或多個連續的空行分隔兩個段落。

public string asParagraphs ( $value )
$value string|null

要格式化的值。

return string

格式化後的結果。

                public function asParagraphs($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/u', "</p>\n<p>", Html::encode($value)) . '</p>');
}

            
asPercent() public method

將值格式化為帶有 "%" 符號的百分比數字。

自 2.0.16 版起,正規化後呈現錯誤的數字會使用不支援 PHP intl 擴充套件 的回退函數格式化為字串。 對於非常大的數字,建議將其作為字串傳遞,並且不要使用科學記號表示法,否則輸出可能不正確。

public string asPercent ( $value, $decimals null, $options = [], $textOptions = [] )
$value mixed

要格式化的值。它必須是一個因數,例如 0.75 將產生 75%

$decimals integer|null

小數點後的位數。如果未給定,位數取決於輸入值,並根據 NumberFormatter::MIN_FRACTION_DIGITSNumberFormatter::MAX_FRACTION_DIGITS 決定,這些可以使用 $numberFormatterOptions 進行配置。如果 PHP intl 擴充套件不可用,則預設值為 0。如果您希望在使用 intl 和不使用 intl 的環境之間保持一致的行為,您應該在此處明確指定一個值。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

                public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asPercentStringFallback((string) $value, $decimals);
    }
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
        if (($result = $f->format($normalizedValue)) === false) {
            throw new InvalidArgumentException('Formatting percent value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    if ($decimals === null) {
        $decimals = 0;
    }
    $normalizedValue *= 100;
    return number_format($normalizedValue, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
}

            
asPercentStringFallback() protected method (available since version 2.0.16)

將值格式化為帶有 "%" 符號的百分比數字的回退。

屬性 $decimalSeparator 將用於表示小數點。 該值會自動四捨五入到定義的小數位數。

protected string asPercentStringFallback ( $value, $decimals null )
$value string|integer|float

要格式化的值。

$decimals integer|null

小數點後的位數。預設值為 0

return string

格式化後的結果。

                protected function asPercentStringFallback($value, $decimals = null)
{
    if (empty($value)) {
        $value = 0;
    }
    if ($decimals === null) {
        $decimals = 0;
    }
    $value = $this->normalizeNumericStringValue((string) $value);
    $separatorPosition = strrpos($value, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($value, 0, $separatorPosition);
        $fractionalPart = str_pad(substr($value, $separatorPosition + 1), 2, '0');
        $integerPart .= substr($fractionalPart, 0, 2);
        $fractionalPart = substr($fractionalPart, 2);
        if ($fractionalPart === '') {
            $multipliedValue = $integerPart;
        } else {
            $multipliedValue = $integerPart . '.' . $fractionalPart;
        }
    } else {
        $multipliedValue = $value . '00';
    }
    return $this->asDecimalStringFallback($multipliedValue, $decimals) . '%';
}

            
asRaw() public method

按原樣格式化值,不進行任何格式化。

此方法僅傳回不帶任何格式的參數。唯一的例外是 null 值,它將使用 $nullDisplay 進行格式化。

public string asRaw ( $value )
$value mixed

要格式化的值。

return string

格式化後的結果。

                public function asRaw($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return $value;
}

            
asRelativeTime() public method

以人類可讀的形式格式化值為日期與現在之間的時間間隔。

此方法可以透過三種不同的方式使用:

  1. 使用相對於 now 的時間戳記。
  2. 使用相對於 $referenceTime 的時間戳記。
  3. 使用 DateInterval 物件。
public string asRelativeTime ( $value, $referenceTime null )
$value integer|string|DateTime|DateTimeInterface|DateInterval|null

要格式化的值。 支援以下值類型

$referenceTime integer|string|DateTime|DateTimeInterface|null

如果指定,當 $value 不是 DateInterval 物件時,該值將用作參考時間,而不是 now

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值無法評估為日期值。

                public function asRelativeTime($value, $referenceTime = null)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    if ($value instanceof DateInterval) {
        $interval = $value;
    } else {
        $timestamp = $this->normalizeDatetimeValue($value);
        $timeZone = new DateTimeZone($this->timeZone);
        if ($referenceTime === null) {
            $dateNow = new DateTime('now', $timeZone);
        } else {
            $dateNow = $this->normalizeDatetimeValue($referenceTime);
            $dateNow->setTimezone($timeZone);
        }
        $dateThen = $timestamp->setTimezone($timeZone);
        $interval = $dateThen->diff($dateNow);
    }
    if ($interval->invert) {
        if ($interval->y >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->language);
        }
        if ($interval->m >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->language);
        }
        if ($interval->d >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->language);
        }
        if ($interval->h >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->language);
        }
        if ($interval->i >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->language);
        }
        if ($interval->s == 0) {
            return Yii::t('yii', 'just now', [], $this->language);
        }
        return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->language);
    }
    if ($interval->y >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->language);
    }
    if ($interval->m >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->language);
    }
    if ($interval->d >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->language);
    }
    if ($interval->h >= 1) {
        return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->language);
    }
    if ($interval->i >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->language);
    }
    if ($interval->s == 0) {
        return Yii::t('yii', 'just now', [], $this->language);
    }
    return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->language);
}

            
asScientific() public method

將值格式化為科學記號數字。

public string asScientific ( $value, $decimals null, $options = [], $textOptions = [] )
$value mixed

要格式化的值。

$decimals integer|null

小數點後的位數。如果未給定,位數取決於輸入值,並根據 NumberFormatter::MIN_FRACTION_DIGITSNumberFormatter::MAX_FRACTION_DIGITS 決定,這些可以使用 $numberFormatterOptions 進行配置。如果 PHP intl 擴充套件 不可用,則預設值取決於您的 PHP 配置。如果您希望在使用 intl 和不使用 intl 的環境之間保持一致的行為,您應該在此處明確指定一個值。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

                public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $value = $this->normalizeNumericValue($value);
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
        if (($result = $f->format($value)) === false) {
            throw new InvalidArgumentException('Formatting scientific number value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    if ($decimals !== null) {
        return sprintf("%.{$decimals}E", $value);
    }
    return sprintf('%.E', $value);
}

            
asShortLength() public method (available since version 2.0.13)

以人類可讀的形式格式化值長度,例如 12 m

這是 asLength() 的簡短形式。

如果您需要將值的單位更改為最小單位的倍數,請檢查屬性 $baseUnits;如果您需要在 UNIT_SYSTEM_METRICUNIT_SYSTEM_IMPERIAL 之間切換,請檢查 $systemOfUnits

另請參閱 asLength()

public string asShortLength ( $value, $decimals null, $options = [], $textOptions = [] )
$value float|integer

要格式化的值。

$decimals integer|null

小數點後的位數。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

throws yii\base\InvalidConfigException

當未安裝 INTL 或不包含所需資訊時。

                public function asShortLength($value, $decimals = null, $options = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_LENGTH, self::FORMAT_WIDTH_SHORT, $value, $decimals, $options, $textOptions);
}

            
asShortSize() public method

以人類可讀的形式將位元組值格式化為大小,例如 12 kB

這是 asSize() 的簡短形式。

如果 $sizeFormatBase 為 1024,則格式化結果將使用 二進制前綴(例如,kibibyte/KiB、mebibyte/MiB、...)。

另請參閱

public string asShortSize ( $value, $decimals null, $options = [], $textOptions = [] )
$value string|integer|float|null

要格式化的位元組值。

$decimals integer|null

小數點後的位數。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

                public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions);
    if ($this->sizeFormatBase == 1024) {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} B', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} KiB', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} MiB', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} GiB', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} TiB', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} PiB', $params, $this->language);
        }
    } else {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} B', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} kB', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} MB', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} GB', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} TB', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} PB', $params, $this->language);
        }
    }
}

            
asShortWeight() public method (available since version 2.0.13)

以人類可讀的形式格式化值重量,例如 12 kg

這是 asWeight() 的簡短形式。

如果您需要將值的單位更改為最小單位的倍數,請檢查屬性 $baseUnits;如果您需要在 UNIT_SYSTEM_METRICUNIT_SYSTEM_IMPERIAL 之間切換,請檢查 $systemOfUnits

public string asShortWeight ( $value, $decimals null, $options = [], $textOptions = [] )
$value float|integer

要格式化的值。

$decimals integer|null

小數點後的位數。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

throws yii\base\InvalidConfigException

當未安裝 INTL 或不包含所需資訊時。

                public function asShortWeight($value, $decimals = null, $options = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_WEIGHT, self::FORMAT_WIDTH_SHORT, $value, $decimals, $options, $textOptions);
}

            
asSize() public method

以人類可讀的形式將位元組值格式化為大小,例如 12 kilobytes

如果 $sizeFormatBase 為 1024,則格式化結果將使用 二進制前綴(例如,kibibyte/KiB、mebibyte/MiB、...)。

另請參閱

public string asSize ( $value, $decimals null, $options = [], $textOptions = [] )
$value string|integer|float|null

要格式化的位元組值。

$decimals integer|null

小數點後的位數。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

                public function asSize($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions);
    if ($this->sizeFormatBase == 1024) {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}', $params, $this->language);
        }
    } else {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{megabyte} other{megabytes}}', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}', $params, $this->language);
        }
    }
}

            
asSpellout() public method

將值格式化為數字拼字。

此函數需要安裝 PHP intl 擴充套件

此格式器不適用於非常大的數字。

public string asSpellout ( $value )
$value mixed

要格式化的值

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

throws yii\base\InvalidConfigException

PHP intl 擴充套件 不可用時。

                public function asSpellout($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $value = $this->normalizeNumericValue($value);
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::SPELLOUT);
        if (($result = $f->format($value)) === false) {
            throw new InvalidArgumentException('Formatting number as spellout failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
}

            
asText() public method

將值格式化為 HTML 編碼的純文字。

public string asText ( $value )
$value string|null

要格式化的值。

return string

格式化後的結果。

                public function asText($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return Html::encode($value);
}

            
asTime() public method

將值格式化為時間。

另請參閱 $timeFormat

public string asTime ( $value, $format null )
$value integer|string|DateTime|DateTimeInterface|null

要格式化的值。 支援以下值類型

  • 表示 UNIX 時間戳記的整數。 根據定義,UNIX 時間戳記始終為 UTC。
  • 可以 解析以建立 DateTime 物件 的字串。 時間戳記假定為 $defaultTimeZone,除非明確給定時區。
  • PHP DateTime 物件。 您可以為 DateTime 物件設定時區,以指定來源時區。

格式器將根據 $timeZone 轉換日期值,然後再進行格式化。 如果不應執行時區轉換,則需要將 $defaultTimeZone$timeZone 設定為相同的值。

$format string|null

用於將值轉換為日期字串的格式。如果為 null,將使用 $timeFormat

這可以是 "short"、"medium"、"long" 或 "full",代表不同長度的預設格式。 它也可以是在 ICU 手冊 中指定的自訂格式。

或者,這可以是帶有 php: 前綴的字串,表示 PHP date() 函數可以識別的格式。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值無法評估為日期值。

throws yii\base\InvalidConfigException

如果日期格式無效。

                public function asTime($value, $format = null)
{
    if ($format === null) {
        $format = $this->timeFormat;
    }
    return $this->formatDateTimeValue($value, $format, 'time');
}

            
asTimestamp() public method

將浮點數格式的日期、時間或日期時間格式化為 UNIX 時間戳記(自 1970-01-01 以來的秒數)。

public string asTimestamp ( $value )
$value integer|string|DateTime|DateTimeInterface|null

要格式化的值。 支援以下值類型

return string

格式化後的結果。

                public function asTimestamp($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $timestamp = $this->normalizeDatetimeValue($value);
    return number_format($timestamp->format('U'), 0, '.', '');
}

            
asUrl() public method

將值格式化為超連結。

public string asUrl ( $value, $options = [] )
$value mixed

要格式化的值。

$options array

標籤選項以名稱-值配對的方式呈現。請參閱 yii\helpers\Html::a()。自 2.0.43 版本起,有一個特殊的選項 scheme 可用 - 如果設定,它將不會傳遞給 yii\helpers\Html::a(),但它將透過正規化 URL 並確保其使用指定的 scheme 來控制連結的 URL 協定部分。請參閱 yii\helpers\Url::ensureScheme()。如果未設定 scheme,則保留原始行為,即當在 $value 中找不到 "://" 字串時,新增 "http://" 前綴。

return string

格式化後的結果。

                public function asUrl($value, $options = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $url = $value;
    $scheme = ArrayHelper::remove($options, 'scheme');
    if ($scheme === null) {
        if (strpos($url, '://') === false) {
            $url = 'http://' . $url;
        }
    } else {
        $url = Url::ensureScheme($url, $scheme);
    }
    return Html::a(Html::encode($value), $url, $options);
}

            
asWeight() public method (available since version 2.0.13)

以人類可讀的形式格式化值重量,例如 12 kilograms

如果您需要將值的單位更改為最小單位的倍數,請檢查屬性 $baseUnits;如果您需要在 UNIT_SYSTEM_METRICUNIT_SYSTEM_IMPERIAL 之間切換,請檢查 $systemOfUnits

public string asWeight ( $value, $decimals null, $options = [], $textOptions = [] )
$value float|integer

要格式化的值。

$decimals integer|null

小數點後的位數。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return string

格式化後的結果。

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

throws yii\base\InvalidConfigException

當未安裝 INTL 或不包含所需資訊時。

                public function asWeight($value, $decimals = null, $options = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_WEIGHT, self::FORMAT_WIDTH_LONG, $value, $decimals, $options, $textOptions);
}

            
attachBehavior() public method

定義於: yii\base\Component::attachBehavior()

將行為附加到此元件。

此方法將根據給定的配置建立行為物件。之後,將呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此組件。

另請參閱 detachBehavior()

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

行為的名稱。

$behavior string|array|yii\base\Behavior

行為配置。這可以是下列其中一項:

return yii\base\Behavior

行為物件

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() public method

定義於: yii\base\Component::attachBehaviors()

將行為列表附加到元件。

每個行為都以其名稱索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的配置陣列。

另請參閱 attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors array

要附加到組件的行為列表

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
behaviors() public method

定義於: yii\base\Component::behaviors()

傳回此元件應表現為的行為列表。

子類別可以覆寫此方法,以指定它們要表現為的行為。

此方法的傳回值應該是由行為名稱索引的行為物件或配置陣列。行為配置可以是指定行為類別的字串,也可以是以下結構的陣列:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

請注意,行為類別必須從 yii\base\Behavior 擴展。行為可以使用名稱或匿名方式附加。當名稱用作陣列鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。

在此方法中宣告的行為將自動(按需)附加到組件。

public array behaviors ( )
return array

行為配置。

                public function behaviors()
{
    return [];
}

            
canGetProperty() public method

定義於: yii\base\Component::canGetProperty()

傳回指示是否可讀取屬性的值。

若符合以下條件,屬性即可讀取:

  • 類別具有與指定名稱相關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可讀屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canSetProperty()

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

是否將行為的屬性視為此組件的屬性

return boolean

屬性是否可讀取

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
canSetProperty() public 方法

定義於: yii\base\Component::canSetProperty()

傳回指示是否可設定屬性的值。

若符合以下條件,屬性即可寫入:

  • 類別具有與指定名稱相關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可寫屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canGetProperty()

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

是否將行為的屬性視為此組件的屬性

return boolean

屬性是否可寫入

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
className() public static 方法
自 2.0.14 版本起已過時。在 PHP >=5.5 版本,請改用 ::class

定義於: yii\base\BaseObject::className()

傳回此類別的完整限定名稱。

public static string className ( )
return string

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
createNumberFormatter() protected 方法

根據給定的類型和格式建立數字格式器。

您可以覆寫此方法以基於模式建立數字格式器。

protected NumberFormatter createNumberFormatter ( $style, $decimals null, $options = [], $textOptions = [] )
$style integer

數字格式器的類型。值:NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE

$decimals integer|null

小數點後的位數。

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return NumberFormatter

已建立的格式器實例

                protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
{
    $formatter = new NumberFormatter($this->locale, $style);
    // set text attributes
    foreach ($this->numberFormatterTextOptions as $attribute => $value) {
        $this->setFormatterTextAttribute($formatter, $attribute, $value, 'numberFormatterTextOptions', 'numberFormatterOptions');
    }
    foreach ($textOptions as $attribute => $value) {
        $this->setFormatterTextAttribute($formatter, $attribute, $value, '$textOptions', '$options');
    }
    // set attributes
    foreach ($this->numberFormatterOptions as $attribute => $value) {
        $this->setFormatterIntAttribute($formatter, $attribute, $value, 'numberFormatterOptions', 'numberFormatterTextOptions');
    }
    foreach ($options as $attribute => $value) {
        $this->setFormatterIntAttribute($formatter, $attribute, $value, '$options', '$textOptions');
    }
    if ($decimals !== null) {
        $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
        $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
    }
    // set symbols
    if ($this->decimalSeparator !== null) {
        $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
    }
    if ($this->currencyDecimalSeparator !== null) {
        $formatter->setSymbol(NumberFormatter::MONETARY_SEPARATOR_SYMBOL, $this->currencyDecimalSeparator);
    }
    if ($this->thousandSeparator !== null) {
        $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
        $formatter->setSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
    }
    foreach ($this->numberFormatterSymbols as $symbol => $value) {
        $this->setFormatterSymbol($formatter, $symbol, $value, 'numberFormatterSymbols');
    }
    return $formatter;
}

            
detachBehavior() public 方法

定義於: yii\base\Component::detachBehavior()

從元件分離行為。

將會調用行為的 yii\base\Behavior::detach() 方法。

public yii\base\Behavior|null detachBehavior ( $name )
$name string

行為的名稱。

return yii\base\Behavior|null

已分離的行為。如果行為不存在,則為 Null。

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() public 方法

定義於: yii\base\Component::detachBehaviors()

從元件分離所有行為。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() public 方法

定義於: yii\base\Component::ensureBehaviors()

確保在 behaviors() 中宣告的行為已附加到此元件。

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
format() public 方法

根據給定的格式類型格式化值。

此方法將調用此類別中可用的 "as" 方法之一來執行格式化。對於 "xyz" 類型,將使用 "asXyz" 方法。例如,如果格式為 "html",則將使用 asHtml()。格式名稱不區分大小寫。

public string format ( $value, $format )
$value mixed

要格式化的值。

$format string|array|Closure

值的格式,例如 "html"、"text" 或返回格式化值的匿名函式。

若要指定格式化方法的其他參數,您可以使用陣列。陣列的第一個元素指定格式名稱,而其餘元素將用作格式化方法的參數。例如,['date', 'Y-m-d'] 的格式將導致調用 asDate($value, 'Y-m-d')

匿名函式簽名應為:function($value, $formatter),其中 $value 是應格式化的值,而 $formatter 是 Formatter 類別的實例,可用於調用其他格式化函式。自 2.0.13 版本起,可以使用匿名函式。

return string

格式化結果。

throws yii\base\InvalidArgumentException

如果此類別不支援格式類型。

                public function format($value, $format)
{
    if ($format instanceof Closure) {
        return $format($value, $this);
    }
    if (is_array($format)) {
        if (!isset($format[0])) {
            throw new InvalidArgumentException('The $format array must contain at least one element.');
        }
        $f = $format[0];
        $format[0] = $value;
        $params = $format;
        $format = $f;
    } else {
        $params = [$value];
    }
    $method = 'as' . $format;
    if ($this->hasMethod($method)) {
        return call_user_func_array([$this, $method], array_values($params));
    }
    throw new InvalidArgumentException("Unknown format type: $format");
}

            
formatNumber() protected 方法 (自 2.0.32 版本起可用)

給定位元組值,格式化人類可讀形式的數字部分。

protected array formatNumber ( $value, $decimals, $maxPosition, $formatBase, $options, $textOptions )
$value string|integer|float

要格式化的位元組值。

$decimals integer|null

小數點後的位數

$maxPosition integer

大小單位的最大內部位置,如果 $formatBase 是陣列則忽略

$formatBase array|integer

計算每個下一個單位的基數,可以是 1000 或 1024,或是一個陣列

$options array

數字格式器的選用配置。 此參數將與 $numberFormatterOptions 合併。

$textOptions array

數字格式器的選用配置。 此參數將與 $numberFormatterTextOptions 合併。

return array

[包含格式化數字的 Yii::t 參數,大小單位的內部位置]

throws yii\base\InvalidArgumentException

如果輸入值不是數字或格式化失敗。

                protected function formatNumber($value, $decimals, $maxPosition, $formatBase, $options, $textOptions)
{
    $value = $this->normalizeNumericValue($value);
    $position = 0;
    if (is_array($formatBase)) {
        $maxPosition = count($formatBase) - 1;
    }
    do {
        if (is_array($formatBase)) {
            if (!isset($formatBase[$position + 1])) {
                break;
            }
            if (abs($value) < $formatBase[$position + 1]) {
                break;
            }
        } else {
            if (abs($value) < $formatBase) {
                break;
            }
            $value /= $formatBase;
        }
        $position++;
    } while ($position < $maxPosition + 1);
    if (is_array($formatBase) && $position !== 0) {
        $value /= $formatBase[$position];
    }
    // no decimals for smallest unit
    if ($position === 0) {
        $decimals = 0;
    } elseif ($decimals !== null) {
        $value = round($value, $decimals);
    }
    // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
    $oldThousandSeparator = $this->thousandSeparator;
    $this->thousandSeparator = '';
    if ($this->_intlLoaded && !isset($options[NumberFormatter::GROUPING_USED])) {
        $options[NumberFormatter::GROUPING_USED] = 0;
    }
    // format the size value
    $params = [
        // this is the unformatted number used for the plural rule
        // abs() to make sure the plural rules work correctly on negative numbers, intl does not cover this
        // https://english.stackexchange.com/questions/9735/is-1-followed-by-a-singular-or-plural-noun
        'n' => abs($value),
        // this is the formatted number used for display
        'nFormatted' => $this->asDecimal($value, $decimals, $options, $textOptions),
    ];
    $this->thousandSeparator = $oldThousandSeparator;
    return [$params, $position];
}

            
getBehavior() public 方法

定義於: yii\base\Component::getBehavior()

傳回具名行為物件。

public yii\base\Behavior|null getBehavior ( $name )
$name string

行為名稱

return yii\base\Behavior|null

行為物件,如果行為不存在則為 null

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() public 方法

定義於: yii\base\Component::getBehaviors()

傳回附加到此元件的所有行為。

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

附加到此組件的行為列表

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
hasEventHandlers() public 方法

定義於: yii\base\Component::hasEventHandlers()

傳回指示是否有名稱事件附加任何處理常式的數值。

public boolean hasEventHandlers ( $name )
$name string

事件名稱

return boolean

是否有任何處理常式附加到事件。

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() public 方法

定義於: yii\base\Component::hasMethod()

傳回指示是否已定義方法的數值。

如果符合以下條件,則定義方法:

  • 類別具有具有指定名稱的方法
  • 附加的行為具有給定名稱的方法(當 $checkBehaviors 為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

屬性名稱

$checkBehaviors boolean

是否將行為的方法視為此組件的方法

return boolean

方法是否已定義

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() public 方法

定義於: yii\base\Component::hasProperty()

傳回指示是否為此元件定義屬性的數值。

如果符合以下條件,則定義屬性:

  • 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的屬性(當 $checkBehaviors 為 true 時)。

另請參閱

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

$checkBehaviors boolean

是否將行為的屬性視為此組件的屬性

return boolean

屬性是否已定義

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
init() public 方法

初始化物件。

在物件使用給定的配置初始化後,此方法會在建構函式的結尾調用。

public void init ( )

                public function init()
{
    if ($this->timeZone === null) {
        $this->timeZone = Yii::$app->timeZone;
    }
    if ($this->locale === null) {
        $this->locale = Yii::$app->language;
    }
    if ($this->language === null) {
        $this->language = strtok($this->locale, '@');
    }
    if ($this->booleanFormat === null) {
        $this->booleanFormat = [Yii::t('yii', 'No', [], $this->language), Yii::t('yii', 'Yes', [], $this->language)];
    }
    if ($this->nullDisplay === null) {
        $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)', [], $this->language) . '</span>';
    }
    $this->_intlLoaded = extension_loaded('intl');
    if (!$this->_intlLoaded) {
        if ($this->decimalSeparator === null) {
            $this->decimalSeparator = '.';
        }
        if ($this->thousandSeparator === null) {
            $this->thousandSeparator = ',';
        }
    }
}

            
isNormalizedValueMispresented() protected 方法 (自 2.0.16 版本起可用)

檢查給定值及其標準化版本的字串表示是否不同。

protected boolean isNormalizedValueMispresented ( $value, $normalizedValue )
$value string|float|integer
$normalizedValue float|integer

                protected function isNormalizedValueMispresented($value, $normalizedValue)
{
    if (empty($value)) {
        $value = 0;
    }
    return (string) $normalizedValue !== $this->normalizeNumericStringValue((string) $value);
}

            
normalizeDatetimeValue() protected 方法

將給定的日期時間值標準化為 DateTime 物件,供各種日期/時間格式化方法使用。

protected DateTime|array normalizeDatetimeValue ( $value, $checkDateTimeInfo false )
$value integer|string|DateTime|DateTimeInterface|null

要標準化的日期時間值。支援以下值類型

$checkDateTimeInfo boolean

是否同時檢查日期/時間值是否附加了一些時間和日期資訊。預設值為 false。如果為 true,則該方法將傳回一個陣列,其中第一個元素是標準化的時間戳記,第二個元素是一個布林值,指示時間戳記是否具有時間資訊,第三個元素是一個布林值,指示時間戳記是否具有日期資訊。此參數自 2.0.1 版本起可用。

return DateTime|array

標準化的日期時間值。自 2.0.1 版本起,如果 $checkDateTimeInfo 為 true,則也可能傳回陣列。陣列的第一個元素是標準化的時間戳記,第二個元素是一個布林值,指示時間戳記是否具有時間資訊,或者僅僅是一個日期值。自 2.0.12 版本起,陣列具有第三個布林值元素,指示時間戳記是否具有日期資訊,或者僅僅是一個時間值。

throws yii\base\InvalidArgumentException

如果輸入值無法評估為日期值。

                protected function normalizeDatetimeValue($value, $checkDateTimeInfo = false)
{
    // checking for DateTime and DateTimeInterface is not redundant, DateTimeInterface is only in PHP>5.5
    if ($value === null || $value instanceof DateTime || $value instanceof DateTimeInterface) {
        // skip any processing
        return $checkDateTimeInfo ? [$value, true, true] : $value;
    }
    if (empty($value)) {
        $value = 0;
    }
    try {
        if (is_numeric($value)) { // process as unix timestamp, which is always in UTC
            $timestamp = new DateTime('@' . (int) $value, new DateTimeZone('UTC'));
            return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp;
        }
        if (
            ($timestamp = DateTime::createFromFormat(
                'Y-m-d|',
                $value,
                new DateTimeZone($this->defaultTimeZone)
            )
            ) !== false
        ) { // try Y-m-d format (support invalid dates like 2012-13-01)
            return $checkDateTimeInfo ? [$timestamp, false, true] : $timestamp;
        }
        if (
            ($timestamp = DateTime::createFromFormat(
                'Y-m-d H:i:s',
                $value,
                new DateTimeZone($this->defaultTimeZone)
            )
            ) !== false
        ) { // try Y-m-d H:i:s format (support invalid dates like 2012-13-01 12:63:12)
            return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp;
        }
        // finally try to create a DateTime object with the value
        if ($checkDateTimeInfo) {
            $timestamp = new DateTime($value, new DateTimeZone($this->defaultTimeZone));
            $info = date_parse($value);
            return [
                $timestamp,
                !($info['hour'] === false && $info['minute'] === false && $info['second'] === false),
                !($info['year'] === false && $info['month'] === false && $info['day'] === false && empty($info['zone'])),
            ];
        }
        return new DateTime($value, new DateTimeZone($this->defaultTimeZone));
    } catch (\Exception $e) {
        throw new InvalidArgumentException("'$value' is not a valid date time value: " . $e->getMessage()
            . "\n" . print_r(DateTime::getLastErrors(), true), $e->getCode(), $e);
    }
}

            
normalizeNumericStringValue() protected 方法 (自 2.0.16 版本起可用)

標準化數值字串值。

protected string normalizeNumericStringValue ( $value )
$value string
return string

標準化的數字值,以字串形式表示

                protected function normalizeNumericStringValue($value)
{
    $powerPosition = strrpos($value, 'E');
    if ($powerPosition !== false) {
        $valuePart = substr($value, 0, $powerPosition);
        $powerPart = substr($value, $powerPosition + 1);
    } else {
        $powerPart = null;
        $valuePart = $value;
    }
    $separatorPosition = strrpos($valuePart, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($valuePart, 0, $separatorPosition);
        $fractionalPart = substr($valuePart, $separatorPosition + 1);
    } else {
        $integerPart = $valuePart;
        $fractionalPart = null;
    }
    // truncate insignificant zeros, keep minus
    $integerPart = preg_replace('/^\+?(-?)0*(\d+)$/', '$1$2', $integerPart);
    // for zeros only leave one zero, keep minus
    $integerPart = preg_replace('/^\+?(-?)0*$/', '${1}0', $integerPart);
    if ($fractionalPart !== null) {
        // truncate insignificant zeros
        $fractionalPart = rtrim($fractionalPart, '0');
        if (empty($fractionalPart)) {
            $fractionalPart = $powerPart !== null ? '0' : null;
        }
    }
    $normalizedValue = $integerPart;
    if ($fractionalPart !== null) {
        $normalizedValue .= '.' . $fractionalPart;
    } elseif ($normalizedValue === '-0') {
        $normalizedValue = '0';
    }
    if ($powerPart !== null) {
        $normalizedValue .= 'E' . $powerPart;
    }
    return $normalizedValue;
}

            
normalizeNumericValue() protected 方法

標準化數值輸入值。

  • 所有 empty 的值都將導致 0
  • numeric 字串將轉換為 float
  • 如果其他所有內容都是 numeric,則將傳回,否則將拋出例外。
protected float|integer normalizeNumericValue ( $value )
$value mixed

輸入值

return float|integer

標準化的數字值

throws yii\base\InvalidArgumentException

如果輸入值不是數字。

                protected function normalizeNumericValue($value)
{
    if (empty($value)) {
        return 0;
    }
    if (is_string($value) && is_numeric($value)) {
        $value = (float) $value;
    }
    if (!is_numeric($value)) {
        throw new InvalidArgumentException("'$value' is not a numeric value.");
    }
    return $value;
}

            
off() public 方法

定義於: yii\base\Component::off()

從此元件分離現有的事件處理常式。

此方法與 on() 相反。

注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用與此萬用字元匹配的純名稱註冊的處理常式將保持不變。

另請參閱 on()

public boolean off ( $name, $handler null )
$name string

事件名稱

$handler callable|null

要移除的事件處理常式。如果為 null,則將移除附加到已命名事件的所有處理常式。

return boolean

如果找到並分離了處理常式

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
on() public 方法

定義於: yii\base\Component::on()

將事件處理常式附加到事件。

事件處理常式必須是有效的 PHP 回呼。以下是一些範例

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

事件處理常式必須使用以下簽名定義:

function ($event)

其中 $event 是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。

自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

另請參閱 off()

public void on ( $name, $handler, $data null, $append true )
$name string

事件名稱

$handler callable

事件處理常式

$data mixed

事件觸發時要傳遞給事件處理常式的資料。調用事件處理常式時,可以透過 yii\base\Event::$data 存取此資料。

$append boolean

是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 false,則新的處理常式將插入到現有處理常式列表的開頭。

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
trigger() public 方法

定義於: yii\base\Component::trigger()

觸發事件。

此方法表示事件的發生。它調用事件的所有附加處理常式,包括類別級別的處理常式。

public void trigger ( $name, yii\base\Event $event null )
$name string

事件名稱

$event yii\base\Event|null

事件實例。如果未設定,將會建立預設的 yii\base\Event 物件。

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}