1

I have designed a WordPress template for my site, and in the function file, I have used the following code to introduce style files to WordPress:

class JSXStyle {

  public function __construct( $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' );

This code works correctly. But when I installed the query-monitor plugin, this code got an error and displayed the following message:

Creation of dynamic property JSXStyle::$MyStyle is deprecated

I don't know how to edit this code to get rid of this error. Is there a way to update this code or should I use another method?

Koala Yeung
  • 7,475
  • 3
  • 30
  • 50
php
  • 171
  • 7
  • Does [this answer](https://stackoverflow.com/a/74879495/4225384) help? – qrsngky Apr 27 '23 at 03:00
  • 1
    Does this answer your question? [PHP Warning Deprecated: Creation of dynamic property is deprecated](https://stackoverflow.com/questions/74878889/php-warning-deprecated-creation-of-dynamic-property-is-deprecated) – Tangentially Perpendicular Apr 27 '23 at 04:07

1 Answers1

2

Starting from PHP 8.2, Dynamic Properties in object is deprecated. That means object properties should be declared before used in assignment (i.e. "creation of dynamic property").

Simply add the JSXStyle::$MyStyle property declaration would be enough:

class JSXStyle {

  // Declare the MyStyle property before use.
  protected string $MyStyle;

  public function __construct( $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' );;
  }
}
Koala Yeung
  • 7,475
  • 3
  • 30
  • 50