Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent of Perl's 'use strict' (to require variables to be initialzied before use)

Tags:

php

Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP:

function mymodule_important_calculation() {
    $result = /* ... long and complex calculation ... */;
    return $resukt;
}

This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable resukt is being used before it is assigned.

So... is there a way to configure PHP to be stricter with variable assignments?

like image 846
pdc Avatar asked Sep 18 '08 11:09

pdc


1 Answers

PHP doesn't do much forward checking of things at parse time.

The best you can do is crank up the warning level to report your mistakes, but by the time you get an E_NOTICE, its too late, and its not possible to force E_NOTICES to occur in advance yet.

A lot of people are toting the "error_reporting E_STRICT" flag, but its still retroactive warning, and won't protect you from bad code mistakes like you posted.

This gem turned up on the php-dev mailing-list this week and I think its just the tool you want. Its more a lint-checker, but it adds scope to the current lint checking PHP does.

PHP-Initialized Google Project

There's the hope that with a bit of attention we can get this behaviour implemented in PHP itself. So put your 2-cents on the PHP mailing list / bug system / feature requests and see if we can encourage its integration.

like image 191
Kent Fredric Avatar answered Oct 24 '22 18:10

Kent Fredric