Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable Typing
#1
PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed .

For example, you can create a multiple-digit number and extract the nth digit from it simply by assuming it to be a string. In the following snippet of code, the numbers 12345 and 67890 are multiplied together, returning a result of 838102050, which is then placed in the variable $number,


Automatic conversion from a number to a string

Quote:<?php
$number = 12345 * 67890;
echo substr($number, 3, 1);
?>
 
At the point of the assignment, $number is a numeric variable. But on the second line,a call is placed to the PHP function substr, which asks for one character to be returnedfrom $number, starting at the fourth position(remembering that PHP offsets start fromzero). To do this, PHP turns $number into a nine-character string, so that substr canaccess it and return the character, which in this case is 1.

The same goes for turning a string into a number and so on. the variable $pi is set to a string value, which is then automatically turned into a floating point number in the third line by the equation for calculating a circle’s area, which
outputs the value 78.5398175.

Automatically converting a string to a number


Quote:<?php
$pi = "3.1415927";
$radius = 5;
echo $pi * ($radius * $radius);
?>

In practice, what this all means is that you don’t have to worry too much about your variable types. Just assign them values that make sense to you and PHP will convert them if necessary. Then, when you want to retrieve values, just ask for them—for example, with an echo statement.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)