PHP

Type Casting-

Type casting is a process of converting a variable from one data type to another data type. Programer can convert values from one type to another explicitly using the cast operator..
implicit and explicit Casting- PHP is a loosely typed language that allows programer to declare a variable and its type simply by using it. PHP automatically converts values from one type to another whenever required. It is called implicit casting.

Type casting in PHP works same way as it does in C. The name of the desired type is written in parentheses before the variable which is to be cast. for example-

Syntax-
To typecast a variable, specify the type you wish the variable to become in
parentheses, followed by the variable, as follows:


(type) $variable

Example-

$num = 10; // $num is an integer
$type = (boolean) $num; // $type is a boolean

echo $type;
?>

Type casting allow for the following data type-
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL
Note- The (unset) cast has been deprecated as of PHP 7.2.0.The (unset) cast will be removed as of PHP 8.0.0.

Variable References-

In simple terms, a variable reference is an alias for a variable. That is, a
variable reference points to the same value as the variable that references
it. Variable references (memory addresses) are commonly used to shorten long variable names
into names that are more practical.

To create a variable reference, do an assignment as usual, add an amper-
sand between the equals sign and the variable to be referenced, as shown
here:-
$alias = & $variable;

Example-

$num = 10; 
$ref = &$num;
echo $ref; // output will be 10;
?>
Back to Top