Tuesday, 21 July 2015

PHP Data Type Conversion

In PHP, variable’s data type is taken depends on the value assigned to it. When this variable is used in some expression where there is an operand of different datatype, then, the type of this variable will automatically be converted at the time of evaluation. For example, If a variable is initialized as string, and used to perform addition with an integer, then it will be taken as integer at the time of evaluation.
If we want to specify the datatype explicitly, we need to convert it after declaration. There are two ways in converting the data type of variable data. One option is type casting as some languages like C, the other way is to use PHP built-in functions. Both are explained in this article as follows.
php_type_conversion
The type casting method is most familiar one to convert the data type and it’s syntax is,
$variable_name = (data_type) $variavle_name
And, another way to change the type of a variable is implemented by PHP built-in function named as settype(). For example,
<?php
$count = "5";
settype($count,'int');
?>
Since $count is initialized with a value enclosed by double quotes, it’s data type is known as String. After executing the second line of above code, it will be an Integer. To confirm it, we can use gettype() method as shown below.
<?php
$count = "5";
echo gettype($count); // output will be 'string'
settype($count,'int');
echo gettype($count); // output will be 'integer'
?>
In later method, type conversion is going to be done in two steps on making a call to the built in function settype() and then the required conversion will take place. Rather, former method will perform type conversion directly by saving the time of calling settype(). So, it is good programming practice to follow the former one for changing the data type.

PHP Variable Scope

The scope of an variable is a metric about which extent the variable can be visible. There are two main categories in variable scope. These are,
  1. Local scope
  2. Global scope
php_variable_scope

Local Scope:

If the variable is recognized with in particular block structure of the program, then it is called as local variable. For example, if the variable declared inside a function will come under the local scope of that function. The number of arguments passed while calling the function, can also be recognized with in the function.

Global scope:

If variables can be recognized throughout the program, then they are in global scope. Variables in global scope can be used inside functions by using PHP global array variable or by using global keyword.

PHP variable scope example:

<?php
$count = 0;
function calculate_count() {
$count = 5;

//will print 5; the value of local variable
echo ++$count; 

// will print 0; the value of global variable declared outside function
echo $GLOBALS["count"]; 
}
calculate_count();
echo $count;
?>
There is an alternative way to access the global variable inside function discuss above. That is, the use of global keyword for variable declaration will help us in this regard. For that, we need to replace below lines,
global $count;
echo $count;
instead of,
echo $GLOBALS["count"];

PHP Globals with EGPCS Information

PHP contains so many predefined global variables which is called as super globals. These variables are started with an underscore (_) symbol, for example, $_GET, $_POST and etc. Unlike, user defined global variables, this kind of super globals can be accessed from PHP function without using global keyword or anything.
php_global_variable
Super globals used to contain array of information about form contents, sessions, cookies and also have some environment information, which is called as EGPCS information in short. The expansion of this acronym is shown in the below list.
  • $_ENV – This variable contains an array of details about the server environment. For example, $_ENV[“HOME”], $_ENV[“PATH_INFO”] and etc.
  • $_GET – This will contain the list of parameters sent as query string with the url.
  • $_POST – This will have the form parameters and its values when the form method is specified as post
  • $_COOKIE – The registered cookies will be loaded with this array.
  • $_SERVER – It contains the server information like, $_SERVER[“REQUEST_METHOD”], $_SERVER[“QUERY_STRING”] and etc.
While executing the PHP program, the global array data are loaded in the order specified using variables_order directive of the PHP configuration file php.ini, and we can control this order and can decide about which of these variable is required to be displayed. To get the elements of $_GET, $_POST and $_COOKIE as a whole into an single associative array, we can use another PHP global variable named $_REQUEST.

PHP Operators

Like other programming languages, PHP includes set of operators that are used to perform operations between one or more values.
PHP has variety of operators based on the operations to be performed. Each operator has precedence, depends on which order an PHP expression will be executed. Sub expressions that hold operators with higher precedence, are having higher priority during execution.
In this article, we are going to see about various type of PHP operators in the order of their precedence.
php_operators

Auto increment/decrement operators in PHP

This operators can be categorized into two types. These are,
  1. pre increment/decrement. For example,
    echo ++i; // increment before print
    echo --i; // decrement before print
  2. post increment/decrement. For example,
    i++; // increment after print
    i--; // decrement after print
  3. Arithmetic Operators

    Addition (+), Subtraction (-), Division (/), Multiplication (*) and modulus (%) operators are coming under this category. Among them, (+,-) has lower precedence than rest of the arithmetic operators.

    PHP Comparison Operators

    Comparison operators are used in conditional expressions of PHP control flow statements like, if, else if, while and so on. For example,
    while(i<=10) {
     ...
    }
    In PHP, the following comparison operators are available.
    <, >, <=, >=, ==, === and !=
    Among them, the first four operators are having higher precedence than others.

    Logical Operators

    PHP includes the following list of logical operators.
    &&, ||, and, or, xor
    Logical operators represented by symbols and words, i.e. (or and ||) return same result, but vary with the precedence. The symbol representation has two level higher precedence than the word representation of logical operators. Because, assignment and combined assignment operators are having higher precedence than the word representation of logical operators.

    Assignment / combined assignment operators in PHP

    Assignment operators are used either to create a copy of PHP variable or to store some value to the new variable.
    Combined assignment operators are used to reduce the length of the expression and number of operands. For example,
    $i = $i + 1;
    //using combined arithmetic operator
    $i += 1;

    Other additional PHP Operators

    Apart from the above list of operators, PHP includes some additional list of operators. These are,
    • Concatenation operator - dot (.) is used to concatenate two or more strings, or to add HTML code into PHP print statements. For example,
      $user = "PHP Guest";
      echo "Hello" . $user . "<br/>";
    • Conditional operator - ( <condition> ? <if true> : <if false> ). For example,
      $output = $_SESSION["userName"]?$_SESSION["userName"]:"ANONYMOUS";
      echo $output;
    • Backticks - PHP supports to execute shell command, by enclosing it within two backticks (``) in a PHP printing statements. For example,
      $output = `ls -al`;
      echo $output;
    • Suppression operator - (@) is used to suppress any warning or error notice from displaying to the browser. For example,
      @split("-",date("d-m-Y");
      By using @ symbol infront of split function which is deprecated, we can suppress the PHP error message.

PHP Type Hinting

As PHP is a loosely typed language, there is no need to specify data type for variable declaration, function declaration or any where. But, using PHP5, we can specify data type that are passed as arguments of PHP functions. This capability is called as type hinting.

Advantages of PHP Type Hinting

  • Using PHP type hinting, we can know the expected argument type of the function at the time of maintenance.
  • Function declaration and usage would be obvious once the code is handover to other developer.
  • Type hinting in PHP makes the code useful for some future reference.

Possible Types for Hinting

In PHP, type hinting is possible only for some specific type of data. For example, functions argument, which is user defined class instance, can be hinted by the name of the class. For example,
function printMenu(Controller $controller) {
...
}
Now, $controller is hinted by the name of the class Controller, meaning that, the function printMenu() can accept only Controller class object as its argument.
Other than the instances of class, PHP type hinting is also applicable for arrays, interfaces and callable functions. Rather, this is not capable for objects like int, float, boolean, string and etc. If we use type hinting for the type int, then the execution will be stopped with the following error.
Catchable fatal error: Argument 1 passed to ... must be an instance of int
php_type_hinting

Example: PHP Type Hinting

We are having two classes named as Controller and Integration. The Controller class holds properties of menu item and the Integration class holds that of integrated software. Both are shown below.
class Controller {
public $menuTitle = "";
public $menuLink = "";
function Controller($menuTitle,$menuLink) {
$this->menuTitle = $menuTitle;
$this->menuLink = $menuLink;
}
}
class Integration {
public $name;
public $version;
function Integration($name,$version) {
$this->name = $name;
$this->version = $version;
}
}
We should save these classes by their name, like, Controller.php and Integration.php. We need to include these classes into a PHP file where we want to implement PHP type hinting. So, let us have a glance into the following code.
include_once("Controller.php");
include_once("Integration.php");

function printMenu(Controller $controller) {
echo "<a href='" . $controller->menuLink . "' target='_blank'>" . $controller->menuTitle . "</a></br/>";
}

function printIntegration(Integration $integration) {
echo "<strong>Integrated Software:</strong> " . $integration->name . " " . $integration->version . "<br/>";
}

$objController = new Controller("PHPPOT","http://phppot.com");
printMenu($objController);
$objController = new Controller("Facebook","http://facebook.com");
printMenu($objController);
$objIntegration = new Integration("jQuery","1.8");
printIntegration($objIntegration);
Here, printMenu() and printIntegration() functions accepts the instances of Controller and Integration classes respectively.
When we create the object by passing the required number of argument, it will be set as the value of class properties. Then, this object will be passed as the argument of the function which expect this particular object hinted by its class name.
For example, printIntegration() function, will work only on receiving instance ofIntegration class. If we pass the instance of Controller class, then the following error will occur.
Catchable fatal error: Argument 1 passed to printIntegration() must be an instance of Integration, instance of Controller given

Output

Save the above PHP file as type_hinting.php. After ensuring that the above files are in PHP root directory, run type_hinting.php. Then, the output will be as follows.
PHPPOT
Facebook
Integrated Software: jQuery 1.8

PHP Variables

Like other programming languages, PHP variables are used to store some values which can be changed or removed by any time.
PHP variables can be declared by specifying the name of the variable starting with a $ sign. For example,
$message = "Welcome to PHPPOT";
$count = 5;
In PHP, we need not to specify the data type of a variable while declaration. Rather, the type of initialized value of that variable can be taken as the variable type. In above example code, $message is string variable where as $count is int, based on their initialized value.
php_variable

PHP variable naming conventions

We need to follow the following rules while declaring variables in PHP script.
  • Variable name can hold alphabets, numbers.
  • Special characters except underscore(_), are not allowed in variable name.
  • We can not reassign PHP $this variable, since it is the pre-assigned.
  • And, a variable name should not contain white spaces.

Types of variables

PHP variables can be categorized by their visibility among the program. We can seen these differences while discussing about variable scope. These are,
  • Global variables – These variables can be recognized from any where in the program. But, within some independent block structures like functions, we need to access this variable using global keyword.
  • Local variables – The variables that are defined within some specific block like functions, are called as local variable. Such kind of variables can be visible with that particular block only.
  • Super globals – These are also like PHP global variables. But, these are predefined global variable, for example, $_GET, $_SERVER and etc. This type of variables can be accessed from anywhere without global keyword or anything.

PHP Scope Resolution Operator

Why this is called as scope resolution operator? This operator is used to refer the scope of some block or program context like classes, objects, namespace and etc. For this reference an identifier is used with this operator to access or reproduce the code inside that scope.
For example, in PHP, the scope resolution operators are used to access the properties and methods of classes.

Accessing PHP Class Variables and Functions using Scope Resolution Operator

We have to use class name to call the variables and functions of the class. For example,
class Organisation {
function getStrength() {
return $strength;
} 
}
$strength = Organisation::getStrength();
This operator is used when no object has been created till the class functions or variables are accessed from outside the scope of the class. Otherwise, it can be called by using class objects like as shown below.
class Organisation {
function getStrength() {
return $strength;
} 
}
$objOrganisation = new Organisation();
$strength = $objOrganisation->getStrength();
As of PHP 5.3.0, the class name can be stored into a PHP variable using which the class properties are called with scope resolution operator. For example,
class Organisation {
function getStrength() {
return $strength;
} 
}
$varOrganisation = "Organisation";
$strength = $varOrganisation::getStrength();
Not only the names of PHP classes and objects that are associated with the scope resolution operator to access class properties and functions. But some set of keywords like, self, static, parent are used for this purpose. But, these keywords are used inside class definition.
php_scope_resolution_operator
This operator is known as Paamayim Nekudotayim named in Hebrew means double colon. In PHP, the errors that occurred related to this scope resolution operator will be displayed to the browser using this name only, that is T_PAAMAYIM_NEKUDOTAYIM, a PHP error constant that denote improper code lines in this regard.
For example, if we use the scope resolution operators unnecessarily, then the following error will be return to the browser.
Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in ... on line...
Or otherwise, if we ignore to use this operator, though it is requires, then the error notice will be,
Parse error: syntax error, unexpected ')', expecting :: (T_PAAMAYIM_NEKUDOTAYIM) in  ... on line...