You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress代码出现“动态属性创建已废弃”警告的解决咨询

解决WordPress中动态属性创建的废弃警告

PHP 8.2及以上版本禁止动态创建未声明的类属性,你的JSXStyle类在构造函数中直接赋值$this->MyStyle = $name,但未提前在类中声明该属性,因此触发了"Creation of dynamic property JSXStyle::$MyStyle is deprecated"警告。以下是两种可行的修复方案:

方案一:显式声明类属性

在类中提前定义$MyStyle属性,明确其访问权限和类型,符合PHP 8.2+的编码规范:

class JSXStyle {
    // 显式声明私有属性,仅类内部可访问
    private string $MyStyle;

    public function __construct( string $name ) {
        $this->MyStyle = $name;
        add_action( 'wp_enqueue_scripts', array( $this, 'register_custom_style' ) );
    }

    public function register_custom_style() {
        wp_enqueue_style( 
            $this->MyStyle, 
            get_stylesheet_directory_uri() . "/css/{$this->MyStyle}.css", 
            array(), 
            '4.0.0' 
        );
    }
}

new JSXStyle( 'style-1' );
new JSXStyle( 'style-2' );
new JSXStyle( 'style-3' );
new JSXStyle( 'style-4' );

方案二:简化代码,移除类结构

由于当前类仅用于绑定样式名到回调函数,完全可以用闭包简化实现,避免类的冗余:

function enqueue_custom_style( string $style_name ) {
    add_action( 'wp_enqueue_scripts', function() use ( $style_name ) {
        wp_enqueue_style( 
            $style_name, 
            get_stylesheet_directory_uri() . "/css/{$style_name}.css", 
            array(), 
            '4.0.0' 
        );
    });
}

enqueue_custom_style( 'style-1' );
enqueue_custom_style( 'style-2' );
enqueue_custom_style( 'style-3' );
enqueue_custom_style( 'style-4' );

两种方案都能消除警告,方案一更贴近你原本的类结构,方案二更轻量简洁,可根据个人编码习惯选择。

内容的提问来源于stack exchange,提问作者php

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:20:00