Sobes.tech
Junior

What is typing in the PHP language?

sobes.tech AI

Answer from AI

Type hinting in PHP refers to a system that defines data types for values and variables. Before PHP 7, PHP was a language with dynamic, weak typing. Starting from PHP 7, strict typing support was added.

Main concepts:

  • Dynamic typing: The variable's type is determined at runtime based on the assigned value. The type can change during program execution.
  • Weak typing: PHP allows implicit type conversions between different data types in certain operations. For example, the string "123" can be automatically converted to the number 123 during arithmetic operations.
  • Strict typing (from PHP 7): Allows declaring expected types for function arguments, return values, class properties, and scalar types (int, float, string, bool). It can be enabled with declare(strict_types=1);. When strict typing is enabled, PHP does not perform implicit conversions between scalar types.

Examples of type hinting in PHP:

<?php

// Dynamic and weak typing (default behavior before PHP 7, or if strict_types is not enabled)
$a = "Hello"; // string
$a = 10; // int - variable type changed
$b = "5";
$c = $a + $b; // 10 + "5" => 15 (implicit conversion of string to number)

echo $c; // Outputs 15

// Strict typing (from PHP 7)
declare(strict_types=1);

function addNumbers(int $x, int $y): int { // Declaring types for arguments and return value
    return $x + $y;
}

// echo addNumbers("10", 20); // Will cause TypeError if strict_types=1

echo addNumbers(10, 20); // Outputs 30

class User
{
    public string $name; // Declaring type for property

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

$user = new User("Alice");
// $user = new User(123); // Will cause TypeError if strict_types=1

Type hinting, especially strict typing, increases code reliability, simplifies reading and debugging, and allows errors to be detected earlier.

What is typing in the PHP language? — PHP - sobes.tech