[PHP/Cast] Be aware of type specification

Aug 29, 2020 PHP string type cast Integer


Are you aware of the type specification when implementing it in PHP? In PHP, if you put a character string in a variable, the variable will be a string type, and if you put an integer, it will be an int type.

PHP does not require (or support) explicit type definitions when defining variables. The type of a variable is defined by the statement in which it is used. This means that if you assign a string to the variable var, var will be a string. If you assign an integer value to var, the variable will be an integer. Quote: PHP: Mutual conversion of types-Manual

So the type of the variable is automatically decided, so some people may not be aware of it. However, I always want to be aware of type specification so that an unexpected error may occur, or it may be a problem when implementing it in a strict type specification language such as TypeScript.

Forcibly change type with cast

If you want to change the type in PHP, you can cast it. *Casting is a relatively aggressive method, so please think of it as one of the methods to use after confirming that the type received in Request is correct.

The following casts can be used.

Quote: PHP: Mutual conversion of types-Manual

For example, if “01234” is defined as a string type and you want to change it to an int type, you can just add (int) before the variable you want to change.

$string = '01234';
$int = (int)$string;
echo $int;

//$int result is int type of "1234".
// *Because it is an int type, the number "01234" is not suitable and becomes "1234".

##in conclusion What did you think. It may be good to implement it while considering the type specification so that it will not be a problem when implementing any language.