Write E_ALL compliant code

Last modified: September 14, 2009 - 13:42

Testing for error notices

By default Drupal is configured to hide E_STRICT notices for the benefit of production sites. On development or testing sites, you should change includes/common.inc from:

<?php
if ($errno & (E_ALL ^ E_NOTICE)) {
?>

to:
<?php
if ($errno & (E_ALL | E_STRICT)) {
?>

Use of if (isset($var)) or if (!empty($var))

(Note: this is still under review by the developers. See discussion and patches here: http://drupal.org/node/34434 . This section will be updated according to the discussion there, until a broad consensus is reached and relevant patches committed).

If you want to test if an array has been set to any value, don't use:

<?php
if ($foo) {}
?>

but:
<?php

// either
if (isset($foo)) {} // $foo=0 (zero) and $foo= '' return TRUE
// or
if (!empty($foo)) {} // use this when 0 or '' are not expected
// and are not valid values for $foo.
?>

The difference between isset() and !empty() is that unlike !empty(), isset() will return TRUE even if the variable is set to an empty string or to the integer 0. In order to decide which one to use, consider whether 0 or '' are valid and expected values for your variable.

The following code is wrong:

<?php
function _form_builder($form, $parents = array(), $multiple = FALSE) {
 
// (...)
 
if ($form['#input']) {
   
// some code (...)
 
}
}
?>

Here, the variable $form is passed on to the function. If $form['#input'] has been set to any value, some code is executed. The problem is that testing this way outputs the following error message:

notice: Undefined index:  #input in includes/form.inc on line 194.

Even though the array $form is already declared and passed to the function, each array's index must be explicitly declared. The previous code should read:

<?php
function _form_builder($form, $parents = array(), $multiple = FALSE) {
 
// (...)
 
if (!empty($form['#input'])) {
   
// some code (...)
 
}
}
?>

Beware!

The function isset() returns TRUE when the variable is set to the integer 0, but FALSE if the variable is set to NULL. In some cases, is_null() is a better choice, especially when testing the value of a variable returned by an SQL query.

 
 

Drupal is a registered trademark of Dries Buytaert.