|
Posted by Umberto Salsi on 11/19/72 11:46
"Treefrog" <info@designstein.co.uk> wrote:
> For a while now I've been wishing PHP had (at least the option to
> enable) strict types. It would help a massive amount in BIG
> applications, and maybe start to taper the millions of lines of crap
> code that's out there.
Starting from the same thought, I realized that a scripting language has
the nice property to allows for fast code development of little programs,
like most the simpler WEB pages indeed are. That's way PHP is so popular.
Faced with the perspective to switch to another strong-typed language
in order to develop some complex applications, I discovered another
development pattern, that is: write your messy code, then check it with
a formal validator.
Problem: no PHP formal validators seem to be available. That's way
I wrote PHPLint, a formal validator for PHP4 and PHP5. It takes your
sources and spots errors and potential problems, like:
unused constants/variables/functions/classes/properties/methods (for
short: "items");
type mismatch in items usage (you can't add a string to a number without
an explicit typecast);
type mismatch in function arguments (you can't pass a string to a function
requiring an array, for example);
all the properties of a class must be declared; their type given by the
initial value or specified through PHPLint meta-code.
This sample of code should give an idea. The comments summaryze the complains
of the validator:
<?php
class Example {
private $aString = "something"; # inferred type: string
public /*. int .*/ $anInt;
public $xxx = 0;
public function __construct(/*. string .*/ $s, $i=0)
{ $this->aString = $s; $this->anInt = $i; }
# inferred method signature: void(string [, int])
public function getString()
{ return $this->aString; }
# inferred method signature: string()
}
$obj = new Example("hello");
# inferred var. type: class Example
$obj->aString = ""; # <-- ERROR: accessing private property
$obj->gggg = 999; # <-- ERROR: no property gggg in class Example
$obj2 = new Example(123); # <-- ERROR: expected arg of type string
$num = 3;
# inferred var. type: int
$num = $obj; # <-- ERROR: type mismatch in assignment
$num += (int) $obj->getString();
$num += $obj->getString(); # <-- ERROR: type mismatch
if( $num === 0 ) { $num = 1; } # ok
if( $num ) { } # <-- ERROR: invalid bool expr
$fp = fopen("data1.txt", "r");
if( $fp === FALSE )
die("can't open data.txt");
$fp = fopen("data2.txt", "r") || die("xxx"); # ERROR: invalid expr
?>
# notice: the property `anInt' used only inside its class, you should make it `private'
# unused property `Example::$xxx'
?>
Regards,
___
/_|_\ Umberto Salsi
\/_\/ www.icosaedro.it
[Back to original message]
|