How can PHP developers optimize their code to avoid repetitive error message table definitions?

To avoid repetitive error message table definitions in PHP, developers can create a centralized error handling mechanism using constants or arrays to store error messages. This allows for easy maintenance and updates of error messages without having to redefine them multiple times throughout the codebase.

<?php

// Define an array to store error messages
$errorMessages = [
    'ERROR_CODE_1' => 'Error message 1',
    'ERROR_CODE_2' => 'Error message 2',
    'ERROR_CODE_3' => 'Error message 3',
];

// Example of using error message in code
$errorCode = 'ERROR_CODE_2';
if (isset($errorMessages[$errorCode])) {
    echo $errorMessages[$errorCode];
} else {
    echo 'Unknown error';
}

?>