Tuesday, 21 July 2015

PHP Variable Varibles

In PHP, it supports to store name of a variable into another variable and there by these variable names can be changed dynamically. This concepts is known as variable variables which we have listed as one of the special features of PHP.

Accessing Variables

Variable Variables are start with double dolor($$) to access the value of the variable, since it is a tree like access like {variable variables name} -> {variable name} -> {variable value}. For example,
$language = "PHP";
$category = "language";
echo $$category;
While running this program, first it will find the value for $category as language as initialized. Then, this value will be joined with the remaining dolor($) sign to find the value of $language to be displayed to the browser using the PHP printing statementfinally.

Accessing Class Properties

We can access the class properties using this variable variables from outside the class. For that, the name of the class property should be stored into a variable being withglobal scope for accessing it even from outside the class. For example,
class College {
var $name = "Arts and Science international";
var $category = "Arts";
}
$objCollege = new College();
$collegeName = "name";
echo $objCollege->$collegeName . "<br/>";
Now the above program will display the value of the name property of the class. Generally, the class properties are accessed by its name without specifying any $ sign. For example, the equivalent code for the same behavior without using any variable variables is as shown below.
//Usual way of accessing class properties
....
echo $objCollege->name . "<br/>";
But, for showing PHP variable variables behavior, we store the name of the class property into a variable $collegeName and there by access the property value by using this variables.
php_variable_variables

Accessing Array Values

Variable variables concept is quite interesting while working with arrays. Why because, since we are using two variables for specifying the name and value separately, there will be more than one possible interpretations in finding values of array elements. Let us, look into this point in detail with an example.
$movies = array("Django","Life of Pi");
$entertainment = "movies";
echo $$entertainment[0];
By default, the interpretation will be done by ${$entertainment[0]}->$m, and since there is no variable $m is defined, an error notice will be returned to the browser, like,
Notice: Undefined variable: m in ..\variable_variables.php on line 4
To resolve this error, we need to compute the value of $entertainment instead of$entertainment[0], by specifying curly braces around it. For example,
...
echo ${$entertainment}[0]; // output: Django
By changing the echo statement of previous program with the specification of program interpretation, it will return the other possible result to the browser.
Similarly, while accessing the class properties which are stored as array values, the variable variables require specification as per the expected result of the developer. For example,
class College {
var $name = "Arts and Science international";
var $category = "Arts";
var $u = "Uncategorized";
var $ugCourses = array("B.A","B.Com","B.Sc");
}
$objCollege = new College();
$courses = "ugCourses";
//Output: Uncategorized
echo $objCollege->$courses[0] . "<br/>";
//Output: B.A
echo $objCollege->{$courses}[0] . "<br/>";
If we use this concept unnecessarily that will increase number of code. Rather, it will be useful if we utilize this property in optimistic manor to reduce line of code.

PHP $_SERVER Variable

$_SERVER is one of the super global variables in PHP. It contains information about headers, server, host and etc. For that, it contains huge list of information with appropriate global indices.
With these global indices, $_SERVER array contains values for the meta variables listed with the specification of common gateway interface. So, while running a PHP script, $_SERVER array will be loaded with the values based on the criteria, like, in which interface the server is running and etc.
Now, we are going to see some of the list of possible indices with $_SERVER array in PHP. And also, we are going to see about the factors based on which these array indices can be categorized.
So, $_server array indices contain information related to the list of following items.
  • Server information
  • Header information
  • Details on PHP page request
  • File name or path information
  • Remote user information
  • HTTP Authentication Details
Let us look into the available indices of $_SERVER array, that falls under each of the above list, one by one.
php_server_array

Server Information in PHP $_SERVER Array

  • GATEWAY_INTERFACE – It holds the name of the common gateway interface version under which the server is running. $_SERVER indices are loaded with the meta variables as specified with this interface.
  • SERVER_NAME – It contains server host name (virtual host name, if any).
  • SERVER_ADDR – contains server IP address.
  • SERVER_PORT – port number of the server, which is 80 by default.
  • SERVER_SIGNATURE – A server generated string will be loaded with this index, when the server generates page as response .
  • SERVER_PROTOCOL – The name of the protocol using which the server is accessed.

$_SERVER Containing Header Information

Under this category, we are going to see the available indices of this PHP global array that are used to store information like, accepted language and encoding technique, charset, connection and etc.
  • HTTP_HOST
  • HTTP_CONNECTION
  • HTTP_ACCEPT_CHARSET
  • HTTP_ACCEPT_ENCODING
  • HTTP_ACCEPT_LANGUAGE
All of the above indices of PHP $_SERVER array will be loaded with the values stored in header, while requesting a page from server. And the captions to refer these values with header content, are Host, Connection, Charset, Encoding, Language, respectively.
  • HTTP_REFERER – For this array index, current page IP address will be set by the user agent, but not guaranteed.
  • HTTPS – It can be loaded with any value if and only if the SERVER_PROTOCOLholds value as https; meaning that, if we request server page by using https protocol, then, this indices will be set.
Added to that, some other array indices in this category, which are used to hold details such as, accepted MIME type, user agent and etc.

Details on PHP Page Request

$_SERVER array contains indices that hold information about page request is as shown below.
  • REQUEST_METHOD – This will contain values from any one of GET or POST methods, using which the request is submitted to the server.
  • REQUEST_TIME – This will represent the time in the form of timestamp, on which the page request is sent.
php_server_array_indices

File name or path information

The indices coming under this category will be used widely to create full URL for the current page. For that we can concatenate strings stored into the $_SERVER array with the following array indices.
  • PHP_SELF – It holds a relative URL of currently executing page with respect to the document root.
  • DOCUMENT_ROOT – holds name of the root directory as specified in PHP configuration file php.ini.
  • QUERY_STRING – It holds the arguments passed with page url after ? mark. For example, if a page URL is like, http://localhost/php_samples/index.php?action=”default”, then, this index will contain action=default.
  • REQUEST_URI – It contains identifier used to access the page resource.
  • SCRIPT_FILENAME – Contains full path of the page running currently.
  • PATH_INFO – It consists information if anything given at the client side. This information will be added in between absolute URL and the URL parameters passed.

Remote User Information Accessing PHP Page from Server

This category includes set of array indices that are used to store name, address and port of the remote user host, from which the page request is generated. And the corresponding indices are as follows.
  • REMOTE_HOST
  • REMOTE_ADDR
  • REMOTE_PORT
And then, it also contains indices for storing authenticated user to access page or to redirect. These array indices are,
  • REMOTE_USER
  • REDIRECT_REMOTE_USER

HTTP Authentication Details

HTTP authentication is used to let user to enter the user name and password to access to requested page. Once, the user entered their user name and password, it will be stored into the global variables, $_SERVER[“PHP_AUTH_USER”],$_SERVER[“PHP_AUTH_PW”], respectively.
HTTP authentication can be any one of basic or digest type authentication. If we choose digest type, then, the $_SERVER[“PHP_AUTH_DIGEST”] will be set. And,$_SERVER[“PHP_AUTH_TYPE”] is used to store the type of authentication as selected.

PHP Type Juggling

In many programming languages, declaring variables requires variable’s data type and name of that variable. And then, variables will be initialized, on need basis, with a value containing same data type as specified on variable declaration. If any type mismatch occurs, then exception will be thrown.

Automatic Type Juggling in PHP

But, in PHP, there is no need of any type specification while PHP variable declaration. Rather, it requires only the name of the variable with its value, if any, to be assigned to them.
php_type_juggling
And, type juggling is one of the features of PHP, provided, to deal with PHP variables. As we have seen already, PHP is an loosely typed language, and hence, capable of taking the data type of the value, as that of the variable, to which that value is assigned.
For example, if we initialize a variable with an integer value, then PHP evaluates the type of the variable as also an integer based on its value. Similarly, if it is a string value, then the same for the variable as well.

Simple PHP Type Juggling Example

Let us look into the following program to know how its behavior according to the PHP type juggling feature.
<?php
$number_of_toys = 10;
$toys_category = "123 Puzzles";
$toys_age_limit = "5.5";
$toys_price = "2e2";
$result1 = $number_of_toys+$toys_category;
$result2 = $number_of_toys+$toys_age_limit;
$result3 = $number_of_toys+$toys_price;
//output integer value: 133
echo $result1."<br/>";
//output float value: 15.5
echo $result2."<br/>";
//output integer value: 210
echo $result3."<br/>";
?>
In the first addition expression of the above PHP program results an integer value, since one of the operand used in this expression is integer. So, the second operand $toys_category is interpreted as an integer, even though it is a string variable on having string value.
While interpreting string as an integer, PHP takes the numeric value with which the string value is started. If the string is not started with numeric values, then, PHP takes 0, while interpreting string as an integer.
Similarly, it second expression, it results float value as the output of that addition, since, one of the operands is float. And then, in third addition, we have added 2e2, returns float value. We can check the type of the results by using PHP variable function gettype().

Explicit Type Casting

While dealing with PHP variables data type, if we don’t want this automatic type juggling feature of PHP, there are several ways for casting variable types by explicitly specifying required data type.
If we want to do such explicit type casting for data type conversion, instead of this automatic interpretation, we can use PHP settype() function. Otherwise, we can also use PHP supported type casting syntax by providing required type within parenthesis, for example,
$str_toys_category = (string) $number_of_toys;

PHP Data Types

This is one boring topic we have in all programming languages – list of data types. It is so boring that no one cares to read it once completely. Sometimes surprisingly developers discover that they have not used a particular data type.
Data types are generally used to represent type of data associated with PHP variables, function’s return type/parameters and etc. We get accustomed to them over the period of use. To the better of all PHP is a loosely typed language, there is no need of specifying data type while declaring variables.

PHP Primitive Data Types

There are eight primitive data types in PHP and it is classified into 3 types.
  1. Scalar Data Types
  2. Compound Data Types
  3. Special Data Types

1. Scalar Data Types

Scalar data types will contain only single value for a variable references.
  1. Integer – PHP integer data type will be used for representing non-fractional numeric values. The range of integer varies with respect to the platform. That is, 2^32 – 2^31 for 32-bit, and, 2^64 – 2^63 for 64-bit.
  2. Float/Double – These data type will represent fractions. For example, 8.99, 0.1 and etc. Double data type supports fractions with more decimal digits.
  3. String – Sequence of bytes enclosed by a pair of single or double quotes is called as PHP string. We can also use heredoc or nowdoc. But double quotes supports variable interpolation.
  4. Boolean – It contains case insensitive TRUE or FALSE values. Zero represents FALSE and any non-zero value represents boolean TRUE.

2. Compound Data Types

Compound data type, as per its name, will have group of data in same type.
  1. Array  PHP Arrays are used to contain group of values with same data type. These group of values can be specified with default numeric indices or some associative indices.
  2. Object – This is another compound data type in PHP. Using PHP object data type, we can have collection of properties set with it.

3. Special Data Types

  • Resource  PHP resource datatype is used to refer external resource data. Example, file resource, database resource and etc.
  • NULL – This type of data contains PHP constant NULL which is case insensitive. We can use is_null() function to check any value if it is NULL.
datatype

Pseudo Types in PHP

Apart from the above major classifications, PHP includes pseudo data types. For that, PHP provides keywords which we can see with the syntax of PHP functions. These are used for representing function’s arguments type or return type.
  • void – We know very well that it is representing empty parameters or return type.
  • mixed – It indicates a PHP function supporting more data types for its arguments and data type.
  • number – This keyword indicates that a function will accept any type of numeric parameter either integer or float, and the same for its return type.
  • callback – This keyword represents that the parameter is having the name of the callback function. But, we should use user defined function name, and not pre-defined PHP constructs like echo(), print()…

Miscellaneous: Data Type Related Functions in PHP

  • gettype() – data type getter returns given variables data types.
  • var_dump() – This function used to get the data type of an expression.
  • is_<type>() – There are several variable functions like is_array(), is_null() and etc., to check a variable with respect to specific data type.
  • settype() – This is the data type setter, used in PHP type conversion.

PHP Namespace

In file system, we have directories or folders to keep related files. Similarly, PHP namespaces are used to have related code blocks of a PHP program that are reusable, like, classes, functions, interfaces under its reference. And, PHP namespaces can also capable of containing constants.
php_namespace

Operations Performed using PHP NameSpaces

With PHP namespaces, we can have the following operations listed below.
  • Grouping related PHP code blocks into one scope or space to refer in future.
  • Creating functions or classes with the same name that already exist with user space or internal code structure without name clashes.
  • Getting current namespace with appropriate PHP keyword or constants.
  • Importing external classes, interfaces and namespaces with alias.
    • Aliasing will avoid name clashes and for shortening the name of imported blocks for easy readability.
    • Aliasing or importing are not applicable for importing external functions.
  • Accessing classes, functions and etc., from global space.

Declaring PHP Namespace

PHP namespaces are declared by namespace keyword followed by name of the namespace. And, importantly, this namespace declaration should be very first line before writing any code to our PHP script. But, there is one exception, that is, it allows PHP declare statement before namespace declaration.
Following PHP code shows how to declare namespace contains of PHP classes, functions and constants.
namespace Database;
class DBController {
public $database_name;
function __construct() {
$this->database_name = "db_namespace";
}
}
function print_database_name($objDBController) {
echo $objDBController->database_name;
}
So, we have created a namespace named as Database, containing classes and functions to handle database related operations. Simply, we have a class with constructor to initialize class properties, while creating objects, and we have a function under this name space to print initialized value.
Since, it is an namespaced class and function with the name of the class will not be treated as a constructor, we have used __construct() magic function. Otherwise, no initialization will be done for any object.

Accessing Namespaced Classes and Functions in PHP

There are various ways in accessing namespaced classes, functions and etc. These are listed below.
  1. Normal Access
  2. Accessing from global space
  3. Accessing with namespace keyword
  4. Accessing with __NAMESPACE__ keyword

Normal Access

This kind of access is very familiar as we have practiced on creating objects to access class members and invoking local functions. For example,
$objDBController = new DBController();
print_database_name($objDBController);
In the first line of above PHP code, we have created an object for the namespaces classe DBController(). Then, the PHP will search for Database\DBController, meaning that, it is searching for the class there exist under current namespace. So, we need not specify namespace’s name, like,
$objDBController = new Database\DBController();
Then, PHP will search for Database\Database\DBController and display class not found error, like,
Fatal error: Class 'Database\Database\DBController' not found...

Accessing from Global Space

For accessing from global space out of this namespace scope, we should add backslashes (\) before classes, functions or some name, what we want to access from global space. For example,
$objDBController = new \Database\DBController();
\Database\print_database_name($objDBController);
The above code will search for the namespaces Database and then specified classes and function under this namespace. So, the above code will create same effect as that of normal access, without any class not found errors.

Accessing with namespace Keyword

PHP namespace keyword is used to get the current namespace. So, we can specify required members of current namespace to be associated with this keyword. And the code is,
$objDBController = new namespace\DBController();
namespace\print_database_name($objDBController);

Accessing with namespace Keyword

This is similar to PHP namespace keyword for getting current namespace. For example,
__NAMESPACE__ . print_database_name($objDBController);
We should not add backslashes following this constant. Instead, we need to separate it by using PHP dot(.) Operator.

foreach in PHP

In PHP, foreach statement is used to iterate over collection of data, like PHP arrays. As per the name of this construct, it will keep on continue with the loop to traverse given input array for each of its element, without any condition.
We have slightly touch about how this is working in PHP, while seeing about PHP loops. In this article, let us see about foreach statement with more details.
Unlike other PHP loop statements, while, do..while and for, this PHP loop statementforeach contains no counters, conditions and no need of increments or decrements, explicitly. Rather, it will iterate with each element, and will be useful, where all the elements of
the array to be traversed unconditionally.
php_foreach

foreach Usage in PHP Script

We can use foreach statement in a PHP program with two various syntax differed based on the iteration behavior for getting array elements in the following type of ways.
  • For getting only array values.
  • For getting both key and value component of each element.

Getting Array Values

foreach syntax for getting only values of a given input array is as shown below.
foreach($input_array as $value) {
...
}
By using this foreach syntax the value of each $input_array element will be stored into $value, for each iteration, and, the array pointer will be moved to point next element of $input_array, to be iterated subsequently. For example,
$input_array = array("apple","orange","grapes");
foreach($input_array as $value) {
$caps_value_array[] = ucfirst($value);
}
print "<b>Getting Array Values</b>";
print "<pre>";
print_r($caps_value_array);
print "</pre>";
In the above PHP example program, there is an input array to be used for the foreachstatement follows. Inside foreach block each value of the array element is applied forPHP case conversion function ucfirst(), and stored into a new array. And the output of this program with the array values, is shown below.
Getting Array Values
Array
(
    [0] => Apple
    [1] => Orange
    [2] => Grapes
)
Since, we have iterated only the value of given $input_array, these values are displayed with default numeric array index.

Getting both key and value

In this method, we can iterate an array or object for getting the element as pair, on each iteration. And, we can use these keys instead of default numeric indices, while displaying resultant array to the browser. The syntax and example program for this method of using PHP foreach is given below which is slightly differed from the previous method.
foreach($input_array as $key=>$value) {
...
}
By using above foreach syntax, the key and value of $input_array is stored into the PHP variables, $key, $value, respectively. For example,
$input_assoc_array = array("fruit1"=>"apple","fruit2"=>"orange","fruit3"=>"grapes");
foreach($input_assoc_array as $key=>$value) {
$caps_assoc_array[$key] = ucfirst($value);
}
print "<b>Getting Array Values</b>";
print "<pre>";
print_r($caps_assoc_array);
print "</pre>";
This kind of usage is mainly for iterating associative arrays in PHP. And the output of this program will be as follows.
Getting Array Values
Array
(
    [fruit1] => Apple
    [fruit2] => Orange
    [fruit3] => Grapes
)

Alternative PHP Syntax Replicating foreach Functionality

Both of the above foreach functionalities can also be obtained by using PHP while statements shown below.
while (list(, $value) = each($input_array)) {
...
}
and
while (list($key, $value) = each($input_array)) {
...
}
But, the only difference is that, the PHP foreach is capable of resetting input array automatically, while start iterating over it. But, before using either of above alternative syntax, we need to call PHP reset() to reset array pointer to the initial position.

Caution:

  • foreach PHP construct only supports data with array or object data type. Passing neither of these data types will cause PHP warning error.
    Warning: Invalid argument supplied for foreach() in ... on line ...
  • PHP errors occurred during failure of foreach execution, will not be controlled by using @ operator.
  • We can iterate with an input array having more than one dimension. The length of the list given to store elements of two dimensional input array, should be identical with the length of the input array.