typecho / typecho/typecho

Typed property Widget\Menu::$title accessed before initialization

Open Beginner friendly
#1,982 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.