Dealing with deprecations

by Gisle Hannemyr

This chapter ....

Table of contents

Introduction

As PHP evolve, parts of the API becomes deprecated. This chapter describes how to deal with those precations.

Deprecations

Each section below describes a specific dprecation and how to repair it.

MySQL

The older MySQL API (characterized by functions starting with mysql_ was deprecated in PHP 5.1 (2012) and removed in PHP 7 (2016).

The current database API provides two sets of functions:

Characteristics:

SO: How to change mysql to mysqli, PHPpclasses.org: How to Convert MySQL to MySQLi.

The newer version is mich more sensitive to schema mismatches. You may need to xxx

Dynamic properties

In PHP, dynamic properties exactly are properties that aren't present in a class' definition, but are set on objects of those classes dynamically, at runtime. IN PHP 8.2, these are deprecated (with some exceptions).

PHP.net

Source: SO: Creation of dynamic property is deprecated.

Example:

The construct $this->file references a property in the class named "file":

$this->file = file_save_upload('file', $form['file']['#upload_validators']);

If it is undeclared in the class' defintion, there will be a deprecation notice:

Deprecated function: Creation of dynamic property …::$file is deprecated in …

To fix it, make sure the entity is declared in the class' defintion. Example:

  /**
   * Provides file entity.
   *
   * @var \Drupal\file\Entity\File
   */
  protected $file;

each()

The each() construct iterates over an array. On each call, it returns an array with the current key and value and advances the internal array pointer to the next position.

Using the this function produces this warning:

The each() function is deprecated.

Example of deprecated use:

while (list($key, $value) = each($items)) { … }

The above construct shows typical usage, and can be replaced by foreach():

foreach ($items as $key => $value) { { … }

Source SO: Resolve deprecated function each()

Curly braces

The following notation is deprecated:

$string = 'abc';
echo $string{0};  // a

It produces this warning:

Deprecated: Array and string offset access syntax with curly braces is deprecated.

To fix, just replace with square brackets:

$array = [1, 2, 3];
echo $array[0];  // 1

Source SO: Array and string offset access syntax with curly braces is deprecated.

Final word


Last update: 2023-09-26 [gh].