How can PHP code be optimized to prevent undefined constant errors?

To prevent undefined constant errors in PHP, you can use the `defined()` function to check if a constant is defined before using it in your code. This helps avoid errors when accessing constants that may not be defined.

if (defined('CONSTANT_NAME')) {
    // Use the constant here
    echo CONSTANT_NAME;
} else {
    // Handle the case when the constant is not defined
    echo 'Constant is not defined';
}