Jump to content

PHP/Variables

From Wikiversity
< PHP

Variables, as mentioned briefly in Introduction to PHP, are a significant feature of 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

[edit | edit source]

In PHP, all variables can be identified by the $ at the beginning of their name. Variables name generally start with a lowercase letter, however this can vary for special variables, which will be explained later. To understand how variables work, take this example:

<?php
echo 'Hello world!';
?>

Here is the same example using variables instead:

<?php
$message = 'Hello world!';
echo $message;
?>

Dynamic typing

[edit | edit source]

A number of other high profile languages (C and C++, for example) use static variable typing. This means that variables have to be given a data type (e.g. number, string of letters, boolean TRUE or FALSE) that will remain the same until they are destroyed.

This is often useful, however PHP does away with static typing and dynamically converts variable types when needed. As explained in the Introduction to PHP article, PHP has different syntax for numbers and strings, however due to PHP's dynamically typed nature, strings can be treated as numbers when needed. Take the following example:

<?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. PHP automatically converts '42' to 42 (a string to an integer). Conversion of clearly abnormal data can produce unexpected results, however. Take the following example:

<?php
$input = '4string2';
// Should multiply 42 by pi, but will produced unexpected results
$thevalue = $input * pi();
echo $thevalue;
?>

Depending on the PHP configuration, PHP may convert '4string2' to integer values before multiplying it by pi, with unexpected results. (On some PHP versions everything after the '4' is ignored and the result is approximately 12.56)

Variable types

[edit | edit source]

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. Strings are surrounded with single quotes when used in PHP.
  • boolean – Can either be true or false, many functions return true or false

Declaration

[edit | edit source]

In a 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
$a;
?>

Scope

[edit | edit source]

Scope refers to what can actually modify a variable, e.g:

<?php
$var = 1;
require 'another_page.php';
?>

The page 'another_page.php' has full access to the variable 'var'.

<?php
$var = 'Test';
function test()
{
 echo $var;
}
test();
?>

OUTPUT-> The above would output nothing, since functions have their own scope, variables outside that scope would not be available.

Globals

[edit | edit source]

You can force functions to access 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

[edit | edit source]

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

[edit | edit source]

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. Examine the following:

<?php
$a = 'Stuff';
$b = &$a; // $b is pointed to $a
$a = 'Stuff2.0'; // $b is now also 'Stuff2.0';
$b = 'Stuff3.0'; // $a is now also 'Stuff3.0';
?>

Learning sessions

[edit | edit source]

None available at present.