Exclusive to PHP 7.4 - Read-only

I developed a PHP library that utilizes the PHP 8.0 readonly keyword, but now I want to ensure compatibility with earlier versions like 7.4.

Although it would be simple to remove the readonly keywords from my code, I believe they serve an important purpose and don't want to discard them.

As someone with a background in C, I considered using macros, but unfortunately, PHP does not support them. I came across this answer which suggests a method for implementing macro-like behavior, but it seems excessive, especially considering my library consists of 26 files.

Is there a straightforward way to have PHP 7.4 ignore the readonly keyword in order to create cross-version compatible code? Something similar to this hypothetical C code snippet:

#if PHP_VERSION < 8
#define readonly /**/
#enif

Perhaps there exists a composer build option that could preprocess files before packaging them?

Answer №1

By default, PHP does not support the type of conditional compilation you are looking for.

One approach could be to preprocess the source files dynamically, utilizing a custom autoloader or Composer hook. The concept is to allow the normal code to execute until it reaches the point where it would typically include the file, then intercept its content and adjust it as needed.

It's important to note that this doesn't have to function like a complete macro system; rather, you can simply enclose the code with clear markers like

/* IF PHP 8 */ readonly /* END IF */
and use a basic regex pattern to identify and modify them:

$php_code = file_get_contents($php_file_being_loaded);
if ( PHP_VERSION_ID < 80000 ) {
    $php_code = preg_replace('#/\* IF PHP 8 \*/.*?/\* END IF \*/#s', '', $php_code);
}
eval($php_code);

Alternatively, you could perform the preprocessing "offline" to generate separate versions of the library automatically: one for PHP 8.0 and higher, and another for PHP 7.4. This process could be straightforward like the previous method, or you could utilize a tool such as Rector, which analyzes and rewrites standard PHP code without additional markers based on predefined rules, including converting it to match a specific PHP version.

Answer №2

PHP does not involve compilation, hence compiler macros are not applicable.
Referencing the Backward Incompatible Changes, a new keyword has been introduced:

readonly is now a reserved keyword. However, it can still be used as a function name.

You have two options: a) refrain from re-assigning its value or b) manage two versions simultaneously.

Answer №3

Many frameworks opt to steer clear of utilizing modern features for this very reason (such as WordPress, Symfony, Laravel). However, if you are determined, your best solution may lie with Composer, allowing you to have a v1.x.x version with composer.json

{
    "require": {
        "php": ">=7.4"
    },
}

as well as a v2.x.x version with composer.json

{
    "require": {
        "php": ">=8.0"
    },
}

By doing composer require lib, Composer will automatically search and install the latest version of your library that is compatible with the local php version and composer.json constraints (-:

The drawback is that you'll need to maintain both v1 and v2 of your library for as long as you wish to support php 7.4 though..

Another approach is to have a loader like lib.php

if(PHP_MAJOR_VERSION >= 8){
    require("lib_modern.php");
} else{
    require("lib_legacy.php");
}

yet again, requiring maintenance for both lib_modern and lib_legacy.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looping through mysql data horizontally within a div tag

Looking for assistance to create a content loop similar to the one on this website? I attempted to use a while() loop, but it ended up displaying vertically without using a table. I suspect this page utilizes thumbnails. What I aim for is to have the it ...

Are all properties in PHP's mysql_fetch_object function converted to strings?

Looking for assistance! I'm facing an issue where mysql_fetch_object is returning all properties as type string. I need to convert the object to JSON while preserving numerical and Boolean values. The parsing of resulting JSON is taking a long time ...

Looking for a way to upload only part of a large file using HTML and PHP

Is it possible to create a PHP script that can upload only the first 1 MB of a very large file? Can this be achieved with a standard form upload in PHP by closing off the connection after 1 MB is uploaded? I have researched various uploaders (HTML5/Java ...

How can I implement PHP handling for "WITH CTE as" SQL queries?

I pasted my SQL query into the PHP code, but it only outputs "0 results". I observed that in Sublime Text editor, all the SQL code appears in the same color (not correct), but as soon as I remove the initial words "WITH CTE as (", the ...

After relocating to the live server, Codeigniter routing is now displaying the error message "file not found"

In the main directory, I have an .htaccess file with the following contents: RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.ph ...

Is there a way to display a Google Map marker after a certain amount of time without needing to refresh the

Is it possible to update Google Map markers without refreshing the map itself every 30 seconds? The markers' latitudes and longitudes are retrieved from a database. Once obtained, these markers are then allocated onto the Google Map. However, the i ...

In PHP, use a while loop to add the £ symbol to a value

I'm struggling to add a "£" sign to the 'Rental Cost per day' field in a table created using data from a csv file with a while loop. Despite multiple attempts, I keep encountering errors. The latest approach involved using an if statement, ...

Child element failing to resize along with parent container

Here is the HTML structure I have for a template.php page within my website. <!DOCTYPE html> <html lang="en"> <head> <title></title> ...... </head> <body> <div id="container"> ...

What is the best way to create dynamic .env files that can easily adapt to different environments instead of

Having multiple .env files (one for Vue and one for Laravel) with 'localhost' hard coded in them is causing accessibility issues from other computers on my network. It would be beneficial to have this set up dynamically, except for production. F ...

Looping through substrings in SQL Server

I could use some assistance with substring functions. Within the guild_data column, there are values stored in binary(4000) format. I am trying to extract specific values starting from position 269 and then selecting every 40th value with a length of 15 ...

Implementing code snippet for managing redirections on both primary and staging WordPress sites

In my functions.php file, I have the following code snippet: function custom_login_redirect( $url, $request, $user ){ if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) { // Valid login ...

Parsing JSON inside a function in PHP involves extracting data from a JSON string and

I found something like this in a *.txt file. function_name({"one": {"id": "id_for_one", "value": "value_for_one"}, ...}); This is how I am accessing the information from the file: $source = 'FILE_NAME.txt'; $json = json_decode(file_get_content ...

sent a data entry through ajax and performed validation using jquery

Is there a solution to validating the existence of an email value using ajax after validation work is completed? Despite attempting to check for the email value and display an alert if it exists, the form continues to submit regardless. See below for the ...

After establishing the connection between Ajax and PHP with a relationship table, the inserted data is not being displayed

I am new to using Ajax and Php and have a question about inserting data into a Mysql table using Bootstrap Modal, Ajax, and Php. Currently, I have a table named "tbl_employee" and a page called "index.php." In the "index.php" page, there is a Bootstrap m ...

Parsing large numbers in JSON data using the json_decode function

Facing an issue while decoding a json string The PHP version being used is 5.4.4-7 and the operating system is Debian amd64. Here is the JSON string: {"status":"success","account":{"buy_title":"KGP ID","birthday":0,"sex":0,"phone_number":"","avatar":"ht ...

iOS authentication token combining PHP

Currently, I am working on an iOS application that requires user login using a unique user ID and password. The existing flow of the process is outlined below: 1) Users input their user ID and password. 2) Upon clicking the login button, a PHP webservice ...

Implementing MySQL in JavaScript code leads to various possibilities

I am working on a web application that requires retrieving values from a MySQL database. The process involves: PHP code generates an HTML page successfully. Clicking a button updates a cookie, which also works. Using the cookie in a MySQL query, which is ...

PDO: Utilizing arrays for data binding in SELECT queries

I am currently working on setting up an array that contains all the necessary parameters for my PDO queries in a separate file. The initial query I am focusing on is a SELECT query that only requires one parameter. $data = array( 'us_id&a ...

load a file with a client-side variable

Is there a way to load a file inside a container while utilizing an argument to fetch data from the database initially? $('#story').load('test.php'); test.php $st = $db->query("select * from users where id = " . $id); ... proce ...

I am facing an issue with the Silverstripe Form Renderwith function not displaying the form or any of its

After attempting to display a form using a template, the following code was utilized: function FacebookForm($fbFields) { $actions = new FieldSet( new FormAction('doFaceBookForm', 'Register') ); $me ...