Wednesday, July 7, 2010

03 - Using Comments, Variables, Variable Types

Using Comments

Comment is a part of your PHP code that will not be translated by the PHP engine. You can use it to write documentation of your PHP script describing what the code should do. A comment can span only for one line or span multiple line.

PHP support three kinds of comment tags :

  1. //
    This is a one line comment

  2. #
    This is a Unix shell-style comment. It's also a one line comment

  3. /* ..... */Use this multi line comment if you need to.

Example : comments.php
Source code : comments.phps

echo "First line
"; // You won't see me in the output
// I'm a one liner comment
Same thing, you won't

see this in the output file
echo "The above comment spans two lines
# Hi i'm a Unix shell-style comment
# Too bad you can't see me

echo "View the source of this file, you'll see no comments here

PHP Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive, so $myvar is different from $myVar.
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Example :

$myvar          = "Hello";
// valid
$yourVar_is-123 = "World";     // valid
$123ImHere      = "Something"; //
invalid, starts with number


Variable Scope
The scope of a variable is the context within which it is defined. Basically you can not access a variable which is defined in different scope.
The script below will not produce any output because the function Test() declares no $a variable. The echo statement looks for a local version of the $a variable, and it has not been assigned a value within this scope. Depending on error_reporting value in php.ini the script below will print nothing or issue an error message.
Example : scope.php

Source code : scope.phps
$a = 1; // $a is a global variable
function Test()
echo $a; // try to print $a, but $a is
not defined here


If you want your global variable (variable defined outside functions) to be available in function scope you need to use the$global keyword. The code example below shows how to use the $global keyword.

Example : global.php
Source code : global.phps
$a = 1; // $a is defined in global scope ...
$b = 2; // $b too
function Sum()

global $a, $b; // now $a and $b are available
in Sum()
$b = $a + $b;

echo $b;

PHP Superglobals
Superglobals are variables that available anywhere in the program code. They are :

  • $_SERVER
    Variables set by the web server or otherwise directly related to the execution environment of the current script. One useful variable is $_SERVER['REMOTE_ADDR'] which you can use to know you website visitor's IP addressExample : ip.php
    Source code : ip.phps

    Your computer IP is
    echo $_SERVER['REMOTE_ADDR'];

  • $_GET
    Variables provided to the script via HTTP GET. You can supply GET variables into a PHP script by appending the script's URL like this :
    or set the a form method as method="get"Example: get.php

    Source code : get.phps
    echo "My name is {$_GET['name']}
    echo "My friend's name is {$_GET['friend']}";

    Note that I put $_GET['name'] and
    $_GET['friend'] in curly brackets. It's necessary to use these curly brackets when you're trying to place the value of an array into a string.

    You can also split the string like this :

    echo "My name is " . {$_GET['name']} . "
    but it is easier to put the curly brackets.

  • $_POST
    Variables provided to the script via HTTP POST. These comes from a form which set method="post"

  • $_COOKIE
    Variables provided to the script via HTTP cookies.

  • $_FILES
    Variables provided to the script via HTTP post file uploads.

  • $_ENV
    Variables provided to the script via the environment.

    Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. It's use the appropriate
    $_POST or $_GET from your script instead of using $_REQUEST so you will always know that a variable comes from POST or GET.

    Contains a reference to every variable which is currently available within the global scope of the script.

You usually won't need the last three superglobals in your script.

Variable Types

PHP supports eight primitive types.
Four scalar types:

  • boolean : expresses truth value, TRUE or FALSE. Any non zero values and non empty string are also counted as TRUE.

  • integer : round numbers (-5, 0, 123, 555, ...)

  • float : floating-point number or 'double' (0.9283838, 23.0, ...)

  • string : "Hello World", 'PHP and MySQL, etc

Two compound types:

  • array

  • object

And finally two special types:

  • resource ( one example is the return value of mysql_connect()

  • NULL

In PHP an array can have numeric key, associative key
or both. The value of an array can be of any type. To create an array use
the array() language construct like this.

Example : array.php
Source code : array.phps

$numbers = array(1, 2, 3, 4, 5, 6);
$age = array("mom" => 45, "pop" => 50, "bro"
=> 25);

$mixed = array("hello" => "World", 2 => "It's

echo "numbers[4] = {$numbers[4]}
echo "My mom's age is {$age['mom']}

echo "mixed['hello'] = {$mixed['hello']}
echo "mixed[2] = {$mixed[2'}";

When working with arrays there is one function I often used. The print_r() function. Given an array this function will print the values in a format that shows keys and elements

Example : printr.php
Source code : printr.phps

$myarray = array(1, 2, 3, 4, 5);
$myarray[5] = array("Hi", "Hello", "Konnichiwa",
"Apa Kabar");

echo '
echo '

Don't forget to print the preformatting tag
before and after calling print_r(). If you don't use them then you'll have to view the page source to see a result in correct format.
Type Juggling
In PHP you don't need to explicitly specify a type for variables. A variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var,
$var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

Example :

$myvar = "0"; // $myvar is string (ASCII 48)
$myvar += 2; // $myvar is now an integer (2)
$myvar = $foo + 1.3; // $myvar is now a float (3.3)

$myvar = 5 + "10 Piglets"; // $foo is integer (15)

Type Casting
To cast a variable write the name of the desired type in parentheses before
the variable which is to be cast.
Example : casting.php

Source code : casting.phps

$abc = 10; // $abc is an integer
$xyz = (boolean) $abc; // $xyz is a boolean
echo "abc is $abc and xyz is $xyz

The casts allowed are:

  • (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

No comments: