Typed property Widget\Menu::$title accessed before initialization
Author: little-gtCreated May 26, 2026Updated May 26, 2026
Labelsbug
Issue: Typed property Widget\Menu::$title accessed before initialization
错误信息
Typed property Widget\Menu::$title must not be accessed before initialization环境
- PHP 8.0+ (启用了类型化属性)
- Typecho 1.3.0 / dev 版
复现条件
当请求的 URL 未匹配到任何后台菜单项时(例如直接访问不存在的后台路径,或某些插件引起的路由异常),Widget\Menu::execute() 中不会给 $title 属性赋值。随后在 admin/header.php:54 中读取 $menu->title 即会触发此错误。
根本原因
Widget\Menu 类中声明了类型化属性(如 public string $title),PHP 要求这些属性在首次访问前必须已被初始化。但在特定代码路径下,$title、$addLink、$currentUrl、$currentMenuUrl 均未被赋值,导致抛出 Error。
修复方案 为所有未初始化的类型化属性提供默认值,确保任何执行路径下属性都有有效状态。
修改文件:var/Widget/Menu.php
class Menu extends Base
{
- public string $title;
+ public string $title = '';
- public ?string $addLink;
+ public ?string $addLink = null;
- private string $currentUrl;
+ private string $currentUrl = '';
- private string $currentMenuUrl;
+ private string $currentMenuUrl = '';
}效果
- 未匹配菜单时,
$title为空字符串,不会抛出错误。 $addLink允许为null,与原有逻辑兼容。$currentUrl/$currentMenuUrl初始化后可供后续方法安全使用。
备注
该修复兼容 PHP 7.4+,不会影响现有功能。建议同步检查 Widget\Menu 中其他可能未初始化的类型化属性。
Source: typecho/typecho