Typing PHP

One of the somewhat unique features of PHP is that it is not a strongly typed language. This means that in the event of a type mismatch, variables are automatically cast into whatever variable type (integer, string, etc.) the interpreter deems most appropriate for the operation. Which is typically fine and in fact a boon to most beginning programmers, and fine for experienced programmers that understand the rules of engagement. However, as I was explaining a concept in PHP to a beginning programmer earlier today, it dawned on me that the code he was looking for:

[geshi lang=php]if (in_array($user,$users)) {
//...[/geshi]

could be improved in terms of intelligibility by being written as:

[geshi lang=php]if (in_array($user_string,$users_array)) {
//...[/geshi]

That is, by building in the intentions of the author with regard to the variable type in to the variable name, the code becomes more legible, understandable, and ultimately maintainable.

The same could be done for functions, by appending the return type to the end of the name.

[geshi lang=php]function foo_bool($bar_int, $baz_string) {
//...[/geshi]

In this way, all the basic information you need about the function (return type and variable input types) is available right in the function definition. While it certainly wouldn't do away with the need for a good description (preferably in a PHPDoc DocBlock) it goes a long way toward explaining the code within the code using simple mnemonics.

Anyone else already using this approach?

§ § §

Categories: PHP.