must not be accessed – 永夜 https://www.shuijingwanwq.com 没有不值得去解决的问题,也没有不值得去学习的技术! Sun, 17 May 2026 06:17:43 +0000 zh-Hans hourly 1 https://wordpress.org/?v=7.0 在 Yii2 中报错:Typed property common\\components\\i18n\\PhpMessageSource::$fallbackBasePath must not be accessed before initialization’ https://www.shuijingwanwq.com/2025/06/16/9143/ https://www.shuijingwanwq.com/2025/06/16/9143/#respond Mon, 16 Jun 2025 01:51:59 +0000 https://www.shuijingwanwq.com/?p=9143 浏览量: 66

1、在 Yii2 中报错:Typed property common\\components\\i18n\\PhpMessageSource::$fallbackBasePath must not be accessed before initialization’。如图1

在 Yii2 中报错:Typed property common\\components\\i18n\\PhpMessageSource::$fallbackBasePath must not be accessed before initialization'

图1

2、为 $fallbackBasePath 提供默认值。修改前 public ?string $fallbackBasePath; 修改后 public ?string $fallbackBasePath = null;

<?php
 
namespace common\components\i18n;
 
class PhpMessageSource extends \yii\i18n\PhpMessageSource
{
    public ?string $fallbackBasePath = null;
 
    protected function loadMessages($category, $language)
    {
        $messages = parent::loadMessages($category, $language);
 
        if (empty($messages) && $this->fallbackBasePath !== null) {
            $fallback = new PhpMessageSource([
                'basePath' => $this->fallbackBasePath,
                'forceTranslation' => $this->forceTranslation,
                'fileMap' => $this->fileMap,
            ]);
            $messages = $fallback->loadMessages($category, $language);
        }
 
        return $messages;
    }
 
    protected function loadFallbackMessages($category, $fallbackLanguage, $messages, $originalMessageFile)
    {
        $fallbackMessageFile = $this->getMessageFilePath($category, $fallbackLanguage);
        $fallbackMessages = $this->loadMessagesFromFile($fallbackMessageFile);
 
        if (
            $messages === null && $fallbackMessages === null
            && $fallbackLanguage !== $this->sourceLanguage
            && strpos($this->sourceLanguage, $fallbackLanguage) !== 0
        ) {
        } elseif (empty($messages)) {
            return $fallbackMessages;
        } elseif (!empty($fallbackMessages)) {
            foreach ($fallbackMessages as $key => $value) {
                if (!empty($value) && empty($messages[$key])) {
                    $messages[$key] = $value;
                }
            }
        }
 
        return (array) $messages;
    }
}
 

3、不再报错。

]]>
https://www.shuijingwanwq.com/2025/06/16/9143/feed/ 0