Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

Strict Typing:

Strict typing, is a feature that allows developers to enforce stronger type checks in their PHP code by default, PHP has a weak typing system, meaning it performs implicit type conversion when necessary, often leading to unexpected behaviour or errors.

With strict typing enabled, PHP requires explicit type declarations for function arguments and return types. This means that functions must receive the exact type of arguments they expect, and they must return values of the specified type. If there’s a mismatch, PHP will throw a fatal error.

Here’s how you enable strict typing in PHP:

  1. For a Single File: You can enable strict typing at the beginning of a PHP file by adding the following declaration:
PHP
<?php

declare(strict_types=1);

?>

This statement tells PHP to enforce strict typing rules for the entire file.

2.Globally: You can also enable strict typing globally in your PHP configuration file ‘php.ini’ by setting the ‘declare(strict_types=1); directive.

Here’s an example demonstrating strict typing:

PHP
<?php

// Enable strict typing for this file

declare(strict_types=1);

// Function with strict typing

function add(int $a, int $b): int {

    return $a + $b;

}

// Using the function with correct types

echo add(2, 3); // Outputs: 5

// Using the function with incorrect types (will throw a fatal error)

// echo add("2", "3"); // Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, string given

?>

With strict typing enabled, PHP will enforce type checks at runtime, ensuring that function arguments and return values adhere to the specified types. This helps catch type-related errors early in the development process, improving code reliability and maintainability.

Strict typing is especially useful in larger codebases or projects where maintaining code consistency and predictability is crucial. However, it’s important to note that strict typing may require adjustments to existing code and may not always be suitable for every project or scenario.