PHP/Variables: Difference between revisions
No edit summary |
No edit summary |
||
| Line 46: | Line 46: | ||
?> | ?> | ||
Does not explicitly define the type of variable ''a''. Of course, the PHP runtime environment recognizes during execution of this line that the programmer provided a string literal as the value for the variable. | Does not explicitly define the type of variable ''a''. Of course, the PHP runtime environment recognizes during execution of this line that the programmer provided a string literal as the value for the variable. If you want to do the same in [[Topic:C++|C++]], you would would have to explicitly declare the variable type: | ||
char[6] a; | char[6] a; | ||
a = "Stuff"; | a = "Stuff"; | ||
Additional equivalent statements combining declaration and initialization of a variable with the same value would be: | |||
char* a = "Stuff"; | char* a = "Stuff"; // using char pointer | ||
char[] b = "Stuff"; // using char array with string literal initialization | |||
char[] c = { 'S', 't', 'u', 'f', 'f', '\0' }; // using char array with array initialization | |||
Notice that C++ requires explicit variable declaration (including variable type) whereas PHP does not. However, it is good practise to declare all variables, as if they are not declared PHP defaults their value to FALSE (0, empty etc.). This is because PHP is a dynamically typed language, and as a result neither type casting nor declaration is enforced. The following is possible: | Notice that C++ requires explicit variable declaration (including variable type) whereas PHP does not. However, it is good practise to declare all variables, as if they are not declared PHP defaults their value to FALSE (0, empty etc.). This is because PHP is a dynamically typed language, and as a result neither type casting nor declaration is enforced. The following is possible: | ||
Revision as of 00:18, 10 December 2006
Variables, as mentioned briefly in Introduction to PHP, are significant for any programming language. They can be used to store all forms of data, and are generally required to perform multiple manipulations on data not hard-coded into a script. This lesson will introduce the basics of variables in PHP.
Basic syntax
In PHP, all variables are denoted by the $ at the beginning of their identifier. They do not need to be declared; they can simply be assigned a value and used from there on. Variables name should start with a lowercase letter; this is not required but (in certain php configurations) prevents clashes with autoglobals (which will be explained later). Here is a basic example of assigning a value to a variable and printing its value onto the page:
<?php $message = 'This is the value of the message variable.'; echo $message; ?>
Variable conversion
PHP also automagically switches variable types when needed. For example, all strings (a string is a series of characters) must be enclosed in quotes (both single quotes and double quotes are supported). However, sometimes values you fetch from external sources will be strings by default but need to be treated as ints (short for integers, which are numerical values) for the purpose of a calculation. This example shows how it can be done:
<?php $input = '42'; $thevalue = $input * pi(); // Will multiply 42 by pi to (by default) 14 decimal places. echo $thevalue; // This should return something along the lines of 131.946891451 ?>
In this instance, we are multiplying the number 42 (in a string variable) by pi to a certain number of decimal places (a float variable - you will learn about this later). Conversion can only occur when possible, however - the following will not work:
<?php $input = '4string2'; // Should multiply 42 by pi, but will probably post a warning or terminate the script with an error $thevalue = $input * pi(); // This should return 0 or false, not print anything or even return an error for the previous line echo $thevalue; ?>
As '4string2' is not a number, PHP will fail to convert it (in order to be multiplied by pi(), which returns a floating point value) and (most likely) return an error or post a warning (depending on PHP's configuration settings in the php.ini file).
Variable types
These are the main types of variables you will be dealing with:
- int - Short for integer. Holds any integer, i.e. a whole numerical value (no decimal places - however, if an int is assigned a number with a decimal place, it will be converted to a float automatically)
- float - Abbreviation of floating point value. Holds any integer WITH a decimal place, to a certain precision (generally 32 digits)
- double - Abbreviation of double precision floating point. Same as above except with far more precision - however, a double value also takes up twice as much memory (generally 8 bytes - obviously insignificant on modern servers)
- string - Holds any array of characters, i.e. a sentence (or two). Generally has an infinite length; however, for compatibility with older servers, limit the size of strings to 32768 characters.
- boolean - Can either be true or false, many functions return true ot false
Declaration
In a more lower-level language like C++, the declaration of the type of each variable is needed. For example, the following code in PHP:
<?php $a = 'Stuff'; ?>
Does not explicitly define the type of variable a. Of course, the PHP runtime environment recognizes during execution of this line that the programmer provided a string literal as the value for the variable. If you want to do the same in C++, you would would have to explicitly declare the variable type:
char[6] a; a = "Stuff";
Additional equivalent statements combining declaration and initialization of a variable with the same value would be:
char* a = "Stuff"; // using char pointer
char[] b = "Stuff"; // using char array with string literal initialization
char[] c = { 'S', 't', 'u', 'f', 'f', '\0' }; // using char array with array initialization
Notice that C++ requires explicit variable declaration (including variable type) whereas PHP does not. However, it is good practise to declare all variables, as if they are not declared PHP defaults their value to FALSE (0, empty etc.). This is because PHP is a dynamically typed language, and as a result neither type casting nor declaration is enforced. The following is possible:
<?php var $a; ?>
Scope
Scope refers to what can actualy modify a variable, e.g:
<?php $var = 1; require 'another_page.php'; ?>
The page 'another_page.php' has full acess to the variable 'var'.
<?php
$var = 'Test';
function test()
{
echo $var;
}
test();
?>
The above would output nothing, since functions have there own scope, variables outside that scope would not be available.
Globals
You can force functions to acess other variables by using the global keyword, e.g:
<?php
$var = 'Test';
function test()
{
global $var;
echo $var;
}
test();
?>
Would output: Test
Or you can use the $GLOBALS array, like this:
<?php
$GLOBALS['var'] = 'Test';
function test()
{
echo $GLOBALS['var'];
}
test();
?>
Static Variables
Static variables exist within a function and are saved after the function executes, e.g:
<?php
function increment()
{
static $a = 0;
echo $a;
$a++;
}
increment(); // 0
increment(); // 1
increment(); // 2
increment(); // 3
?>
If the variable 'a' was not static, it would echo 0 each time.
Referencing
On a sidenote, a less used feature of PHP (and, indeed, many lower level programming languages) is memory address referencing. The idea is that every variable is stored at a certain address in memory. Now, say you wanted to have a variable that always remained the same values as another, you could just store point it at the same address - any changes at that address, i.e. any change to the value of the first variable, would be reflected in the other variable (but not vice versa). Examine the following:
<?php $a = 'Stuff'; $b = &$a; // $b is pointed to $a $a = 'Stuff2.0'; // $b is now also 'Stuff2.0'; ?>
Learning sessions
None available at present.