About Lesson
PHP Heredoc ,Type Casting and Type Juggling:
PHP Heredoc:
Heredoc is a way to define a string in PHP that allows for multiline text without having to escape special characters. It’s useful when you have a large block of text that you want to assign to a variable. To use heredoc, you start with <<< followed by an identifier, then write multiline text, and end it with the same identifier on a line by itself. Example:
PHP
‘’$myText=<<<EOT(end of text)
This is a heredoc example.
You can write multi lines text here.
And you don’t need to escape charaters like “or’.
EOT; ‘ ‘ ‘
In this example , ‘$mytext’ will contain the multiline text enclosed between ‘<<<EOT’ and ‘EOT;’.
Type Casting:
Type casting in PHP refers to converting a variable from one data type to another.
Here’s a simple tabular representation of basic type casting in PHP:
Function | Descripation | Example |
‘int’ or ‘intval( )’ | Cast to integer | ‘php $floatVar= 3.14; $intVar= (int)$floatVar;’ |
‘(float)’ or ’floatval( )’ | Cast to float | ‘php $intVar= 42; $floatVar = (float)$intvar;’ |
‘(string)’ or ‘strval( )’ | Cast to string | ‘php $intVar = 42; $strVar = (string)$intVar;’ |
‘(bool)’ or ‘boolval( )’ | Cast to boolean | ‘php$strVar= “true”; $boolVar= (bool)strVar;’ |
‘(array)’ | Cast to array | ‘php $var=42; $arrayVar = (array)$var;’ |
‘(object)’ | Cast to object | ‘php $arrayVar = [“key” => “value”]; 4objVar=(object)$arrayVar;’ |
Explanation:
- ‘(type)’ is the casting syntax. You can use the corresponding functions like ‘intval()’, ‘floatval()’, etc.
- The data inside the parentheses is the variable or expression you want to cast.
- Be cautious when casting from float to int, as it truncates (removal of decimal part) the decimal part.
Type Juggling:
Type juggling in PHP means that the language automatically converts variables from one data type to another when needed. For example:
PHP
$var1 = "10"; // $var1 is a string
$var2 = 5; // $var2 is an integer
$result = $var1 + $var2; // PHP automatically converts $var1 to an integer before addition
echo $result; // Output: 15