Skip to content
PHP Misconceptions

Chapter 01

Can PHP Be Typed?

Compare strict and coercive PHP calls, check a list with PHPStan, and validate form input before passing it into typed code.

PHP is dynamically typed and lets you declare types on parameters, return values and properties. PHP enforces those declarations at runtime. Even in a strict file, $value = 3; and then $value = '3'; are both valid assignments. PHP checks the value when, for example, you pass it to a parameter declared as int. PHP type declarations

A form handler illustrates where three kinds of checks belong.

CheckWhere to use itExample
Input validationWhere raw data enters your applicationParse the string '3' and check that the number is within the allowed range.
Native type declarationsOn the parameters, returns and properties your code relies onMake the pricing method take a quantity declared as int.
Static analysisIn your editor or build checks, before running the applicationHave PHPStan check that code passes a list of integers to a batch pricing function.

The series uses PHP 8.6. The standalone examples in this chapter also run on PHP 8.2 or later, which supports the readonly class used below. The PHPStan walkthrough uses curl. PHP 8.2 migration guide

If you already have the checkout, open a terminal at its root and run php --version. For a new checkout, use these commands.

Terminal window
git clone https://github.com/dalehurley/codewithphp.git
cd codewithphp
php --version

A unit costs 1,250 cents. Two PHP files each call forQuantity(int $quantity) with the integer 3 and then with the string "3". One file starts with declare(strict_types=1). What will each file do with the string?

Both files load the same UnitPrice class.

<?php
declare(strict_types=1);
final readonly class UnitPrice
{
public function __construct(public int $cents)
{
if ($cents < 0) {
throw new InvalidArgumentException('Unit price must be non-negative.');
}
}
public function forQuantity(int $quantity): int
{
return $this->cents * $quantity;
}
}

In the constructor, public int $cents declares both a parameter and a property. In forQuantity(int $quantity): int, the first int describes the argument and the second describes the return value. All prices and totals are in cents.

Run these files from the checkout root.

Terminal window
php code/php-misconceptions/types.php
php code/php-misconceptions/types-coercive.php
Reveal the results and watch the animation

The strict file prints 3750 for the integer, then prints The quantity call raised a TypeError. after catching the error for the string. The coercive file prints 3750 twice.

The animation shows the value returned by the method. The CLI scripts use echo to print it.

Animation transcript. The animation shows the method forQuantity(int $quantity): int and the expression (new UnitPrice(1250))->forQuantity("3"). With the default calling mode, PHP converts the string to an integer and the method returns 3750. The animation then shows declare(strict_types=1); above the same expression in the calling file. This time PHP raises TypeError before the method body runs. The last frame asks which file makes the call.

Open types.php and types-coercive.php. They run the same calls. The strict file adds declare(strict_types=1); after <?php. The coercive file leaves it out.

For a direct call to a user-defined function or method, the calling file controls scalar argument coercion. The declaration in UnitPrice.php applies to calls made in that file. Try the following values by changing $input in each caller.

Value for $inputStrict callerCoercive caller
3Returns 3750Returns 3750
"3"Raises TypeErrorConverts to 3 and returns 3750
"three"Raises TypeErrorRaises TypeError

Strict scalar checking still accepts an int for a float parameter. Operators have their own rules. In the strict file, "3" == 3 evaluates to true, and "3" === 3 evaluates to false. Try both with var_dump(). Strict typing rules · Comparison operators

To see a return check, save this as return-quantity.php in a scratch directory.

<?php
declare(strict_types=1);
function quantity(): int
{
return '3';
}

From that directory, run php -r 'require "return-quantity.php"; quantity();'. The caller uses the default coercive mode, but quantity() raises a TypeError because the strict file that defines it declares an int return and returns a string. PHP return type example

A union such as int|string accepts either type. Passing "3" to that union keeps it as a string, even in a coercive call, because it already matches the string member. An intersection such as Countable&Iterator requires a single object that implements both interfaces. An ArrayIterator satisfies that declaration. PHP type system · Coercion with unions

Try these two commands from the checkout root.

Terminal window
php -r 'require "code/php-misconceptions/UnitPrice.php"; new UnitPrice(-1);'
php -r 'require "code/php-misconceptions/UnitPrice.php"; echo (new UnitPrice(1250))->forQuantity(-1), PHP_EOL;'
ExpressionResult
new UnitPrice(-1)The constructor throws InvalidArgumentException because the unit price must be non-negative.
(new UnitPrice(1250))->forQuantity(-1)Returns -1250 because -1 is an integer and the method has no quantity range check.

If an order can only contain non-negative quantities, check that rule before pricing. Put the rule inside the pricing method too if it must hold for every caller.

quantity-list.php prices a batch by forwarding each array element to forQuantity(). Its function declares the native type array and adds a more specific PHPDoc contract for PHPStan.

/** @param list<int> $quantities */
function totalQuantities(UnitPrice $price, array $quantities): int
{
$total = 0;
foreach ($quantities as $quantity) {
$total += $price->forQuantity($quantity);
}
return $total;
}

A list<int> has integer values and sequential keys starting at zero. The supplied script passes ['3']. The native array parameter accepts it, then the strict call inside the loop raises TypeError for the string element. PHPStan list types

Terminal window
php code/php-misconceptions/quantity-list.php

From the checkout root, download the PHPStan version used for this example and analyse both the class and the script.

Terminal window
mkdir -p tmp/php-types
curl -fL https://github.com/phpstan/phpstan/releases/download/2.3.7/phpstan.phar -o tmp/php-types/phpstan.phar
php tmp/php-types/phpstan.phar analyse --level=5 --no-progress -v \
code/php-misconceptions/UnitPrice.php code/php-misconceptions/quantity-list.php

PHPStan reports argument.type at the call to totalQuantities(). It expects list<int> and receives array{'3'}. That is the expected first result, with exit status 1.

Change the last line in quantity-list.php to pass [3] and rerun the PHP and PHPStan commands. PHP prints 3750, and PHPStan reports no errors with exit status 0. Then try [2 => 3]. PHP still prints 3750, but PHPStan flags the key sequence because it starts at 2. PHPStan checks the contract against the code it analyses. Validate data from forms, files or APIs before passing it into a function that relies on that contract. PHPStan command-line usage · PHPDoc generics

In code/php-misconceptions/types.php, set $input = 3;. The second call prints its return value on success. When you rerun the script, expect two lines of 3750.

Validate a quantity before calling typed code

Section titled “Validate a quantity before calling typed code”

Run validate-quantity.php with each input. The CLI argument stands in for a string received from a form.

Terminal window
php code/php-misconceptions/validate-quantity.php 3
php code/php-misconceptions/validate-quantity.php 0
php code/php-misconceptions/validate-quantity.php 3abc
php code/php-misconceptions/validate-quantity.php -1

The first two commands print 3750 and 0. The other two print a validation error and exit with status 1. The script uses FILTER_VALIDATE_INT with an allowed range of 0 to 1,000. On success the filter returns an integer. The condition $quantity === false distinguishes validation failure from a valid zero. A cast such as (int) '3abc' yields 3, so casting alone would silently accept that input. PHP integer validation

A form submits ['3', '0', '3abc', '-1']. Where would you check the raw entries, enforce the pricing rules and verify the list contract? Assume the form rejects the whole batch when any entry is invalid.

Check your answer
  1. In the form handler, verify that the field contains an array and that each entry is a string. Apply the same integer and range validation from the single-quantity example to each entry. Reject the batch when an entry fails. Otherwise, append each parsed integer to a new array with $quantities[] = $quantity to create consecutive keys.
  2. In UnitPrice, keep the constructor’s non-negative price check and the method’s native int signature. If negative quantities are invalid for every caller, add a guard for $quantity < 0 in forQuantity().
  3. At the call to totalQuantities(), PHPStan can check that the code passes a list<int>. For a corrected batch of ['3', '0'], validation produces [3, 0] and the function returns 3750 cents.

Is PHP Always Slow?

Report a problem with this example