Current Location: Home> Latest Articles> PHP Variable Type Definition: Type Casting, settype() and Type Declarations Explained

PHP Variable Type Definition: Type Casting, settype() and Type Declarations Explained

M66 2025-07-29

PHP Variable Type Definition: Type Casting, settype() and Type Declarations Explained

In PHP, the variable type is dynamically assigned. This means you don't need to specify the type when declaring a variable. However, in some cases, you may want to explicitly define the type of a variable. This article will introduce several common methods for defining variable types in PHP, with examples.

Using Type Casting

PHP provides type casting functions that allow you to convert a variable into a different type. The most commonly used casting types include:

  • (int): Casts the variable to an integer
  • (float): Casts the variable to a floating-point number
  • (string): Casts the variable to a string
  • (array): Casts the variable to an array
  • (bool): Casts the variable to a boolean

Here are some examples of type casting:

$var = "123";
$var_int = (int)$var; // Converts the string to an integer
echo $var_int; // Outputs 123
$var = 3.14;
$var_string = (string)$var; // Converts the float to a string
echo $var_string; // Outputs "3.14"
$var = "1,2,3";
$var_array = (array)$var; // Converts the string to an array
print_r($var_array); // Outputs Array ( [0] => 1,2,3 )
$var = 0;
$var_bool = (bool)$var; // Converts the integer to a boolean
echo $var_bool; // Outputs false

Using settype() Function

The settype() function in PHP is used to explicitly convert a variable to a specified type. Unlike type casting, the settype() function modifies the original variable. Here is an example using settype():

$var = "123";
settype($var, "int"); // Converts the variable to an integer
echo $var; // Outputs 123

Using Type Declarations

Starting from PHP 7, you can use type declarations to explicitly specify the types of function parameters and return values. This ensures that the parameters are of the correct type and improves code readability and safety. Here's an example:

function addNumbers(int $a, int $b): int {
    return $a + $b;
}
$result = addNumbers(2, 3); // Parameters and return value must be integers
echo $result; // Outputs 5

It is important to note that type declarations only affect the function parameters and return values, and do not apply to other variables within the function body.

Conclusion

In PHP, defining variable types can be achieved in various ways, including type casting, using the settype() function, and type declarations. The appropriate method can be chosen based on the use case. Type declarations enhance code readability and safety, reducing type-related errors.