Typed property Widget\Menu::$title accessed before initialization
Nobody has claimed this yet.
- Dominant language
- PHP
- Stars
- 12.4k
- Forks
- 2.1k
- PR merge metrics
- No merged PRs in 30d
Description
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 中其他可能未初始化的类型化属性。
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with var/Widget/Menu.php and inspect Widget\Menu::execute(), then check the access at admin/header.php:54. Initialize the four typed properties with the defaults shown in the issue, and verify that an unmatched backend URL no longer raises the initialization error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 88/100