Function Named readonly is Deprecated in PHP 8.6

Function Named readonly is Deprecated in PHP 8.6

In PHP, readonly is a reserved keyword, used since PHP 8.1 to declare readonly properties. An exception was made for functions at the time. WordPress already had a function named readonly, and making the name reserved everywhere would have broken it, so PHP 8.1 added a special rule which still allows a function to use that name. No other keyword in PHP has such a rule.

Since PHP 8.6, declaring a function named readonly is deprecated. Consider the following function which renders the readonly attribute of an HTML input:

<?php

function readonly(bool $condition): string
{
    return $condition ? ' readonly' : '';
}

echo '<input type="text" value="John"'.readonly(true).'>';

Output:

Deprecated: Calling a function "readonly" is deprecated since 8.6 in main.php on line 3
<input type="text" value="John" readonly>

The deprecation is raised where the function is declared, not where it is called. A function named readonly which is never called still produces the deprecation.

The name is matched case-insensitively, so functions named READONLY or ReadOnly are deprecated as well, and the message repeats the name exactly as it was written. A function declared inside a namespace is deprecated too, because the restriction applies to the name itself. Names which only contain this word, such as readonlyAttribute, are not affected. A method named readonly is not affected either, because the restriction applies only to functions.

The example can be fixed by renaming the function:

<?php

function readonlyAttribute(bool $condition): string
{
    return $condition ? ' readonly' : '';
}

echo '<input type="text" value="John"'.readonlyAttribute(true).'>';

Leave a Comment

Cancel reply

Your email address will not be published.