Dynamic type system
PHP has a dynamic type system. This means that a type of a value stored in a variable is not defined until a program execution reach that variable. Also this means that you can put into a variable a value of any type no matter what value did that variable hold before. Consider this example:
$var = 100;
if(rand() % 2)
{
$var = 'Jennifer';
}
elseif(rand() % 3)
{
$var = [1, 2, 3, 4, 5];
}
# Is $var a number, a string, or an array here?
A dynamic type system has its own pros and cons which discussion is outside of the scope of this lesson. For example, in C++ such a thing won't compile:
auto var = 100;
var = "Jennifer"; // Error: type mismatch
Which means that in C++ a compiler controls type integrity for you and you're not allowed to jump from one type to another type dealing with the same variable. PHP on the other hand gives you such a freedom. However, more freedom means more responsibility, and you have to control types by yourself, or else you could bump into a runtime error:
$year = 365;
$period = 30;
if($is_weekly_payment)
{
$period = 'week';
}
# $period is converted to a number. If it holds 'week' value
# then it will be converted to 0 since 'week' is not a number,
# and you'll get 'Division by zero' runtime error.
echo $year / $period;
So, you should use the same variables to store values of the same type, unless you have a really good reason to do otherwise.