PHP Best Practices #2: Strictures

Make sure PHP is reporting all errors and warnings.

Warnings and notices are PHP’s way of letting you know that you are utilising features in a non-standard way. If your code is omitting errors, then it should be fixed as soon as possible. Strict warnings are a class of errors that are turned off by default in most PHP installations. Turning on strict warnings gives you another level of error reporting, which is helpful to prevent you from using misusing functions, making sure your code is compatible with future PHP versions.

In the example here, using date() without explicitly setting a timezone will result in an E_STRICT warning. In this case, we are using a function called strictErrors to tell PHP to report all error types.

Example

    <?php
    
    function strictErrors() {
        $reporting_level = E_ALL;
        
        // if version of PHP < 6, explicity report E_STRICT
        if ( version_compare( PHP_VERSION, '6.0.0', '<' ) ) {
            $reporting_level = E_ALL | E_STRICT;
        }
        
        return error_reporting( $reporting_level );
    }
    

    // turn on strict error and warnings
    strictErrors();
    
    // produces strict warning
    echo date( "d-M-Y" );
    
    // no warning
    date_default_timezone_set( 'Europe/London' );
    echo date( "d-M-Y" );
    
    ?>

Further information

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.