The first programming language I ever worked with was QuickBasic. I copied programs out of the back of a book to create everything from digital artwork to a password-protected Rolodex application. It was great!
But my coding skills sucked.
I never did master subroutines in QuickBasic, so anything beyond a simple program quickly grew out of control. I abandoned the world of programming for a few years until I fell back into it with PHP and had to learn everything over again.
Luckily, PHP was relatively easy to learn! I could write clear code in an easy-to-follow outline and I never had to worry about type information or compiling or memory management. These were all topics that had kept me away from other, "professional" programming languages in the past.
As my coding skills improved, however, so did my understanding of the value of these requirements.
PHP 7
PHP 7 introduced the concept of strict typing by way of type annotations. In the past, developers could identify the types of data passed into and out of a function using documentation alone:
/**
* This function takes in a number and a string
* and produces a log message.
*
* @param int $code Error code
* @param string $msg Error message
*
* @return string
*/
function produce_message($code, $msg)
{
}
With the newer version of PHP, developers can now annotate their code directly and specify both the types required for function input and returned after function execution:
/**
* This function takes in a number and a string
* and produces a log message.
*
* @param int $code Error code
* @param string $msg Error message
*
* @return string
*/
function produce_message(int $code, string $msg): string
{
}
Even better, developers can identify their code as requiring "strict" mode, meaning PHP will not attempt to silently coerce one type to another. In its default mode, the following code is perfectly valid:
function sum(int $first, int $second)
{
return $first + $second;
}
$third = sum(1, '2'); // Now contains 3
Adding a strict type declaration …
declare(strict_types=1);
… will cause the same code to instead produce a runtime exception!
Other Types
Even newer versions of PHP support newer type information. PHP 7.1 introduced the idea of nullable types – data that can either be of one type, or an explicit NULL.
PHP 7.2 introduces a more abstract "object" type, allowing for something that more closely resembles dynamic typing even in a strictly-typed world.
Do you use type information in your PHP code? What drove you to make the change (or what is preventing you from taking the jump)?