Encapsulation in PHP

  • Encapsulation is a concept where we encapsulate all the data and member functions together to form an object.
  • Wrapping up data member and method together into a single unit is called Encapsulation.
  • Encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system.
  • Binding the data with the code that manipulates it.
  • It keeps the data and the code safe from external interference.

Example 1

<?php  
class person  
    {  
      public $name;  
      public $age;  
      function __construct($n, $a)  
         {  
           $this->name=$n;  
           $this->age=$a;  
         }  
public function setAge($ag)  
   {  
   
   $this->ag=$ag;  
   
   }  
   
public function display()  
   
{  
   
    echo  "welcome ".$this->name."<br/>";  
   
    return $this->age-$this->ag;  
   
}  
   
}  
   
$person=new person("sonoo",28);  
   
$person->setAge(1);  
   
echo "You are ".$person->display()." years old";  
   
?>  

Output:

Welcome sonoo

You are 27 years old

PHP Form Handling

We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST.

The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post request $_POST.

PHP Get Form

Get request is the default form request. The data passed through get request is visible on the URL browser so it is not secured. You can send limited amount of data through get request.

Let’s see a simple example to receive data from get request in PHP.

<form action="welcome.php" method="get">  
Name: <input type="text" name="name"/>  
<input type="submit" value="visit"/>  
</form>   

PHP Post Form

Post request is widely used to submit form that have large amount of data such as file upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You can send large amount of data through post request.

Let’s see a simple example to receive data from post request in PHP.

<form action="login.php" method="post">   
<table>   
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>  
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>   
<tr><td colspan="2"><input type="submit" value="login"/>  </td></tr>  
</table>  
</form>  
<?php  
$name=$_POST["name"];//receiving name field value in $name variable  
$password=$_POST["password"];//receiving password field value in $password variable  
  
echo "Welcome: $name, your password is: $password";  
?>  

Output:

php form
php login form handling

PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.

Definition

  1. $emp = array  
  2.   (  
  3.   array(1,”sonoo”,400000),  
  4.   array(2,”john”,500000),  
  5.   array(3,”rahul”,300000)  
  6.   );  

PHP Multidimensional Array Example

Let’s see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3 columns.

IdNameSalary
1sonoo400000
2john500000
3rahul300000

  

<?php    
$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
  
for ($row = 0; $row < 3; $row++) {  
  for ($col = 0; $col < 3; $col++) {  
    echo $emp[$row][$col]."  ";  
  }  
  echo "<br/>";  
}  
?>  

Output:

1 sonoo 400000 
2 john 500000 
3 rahul 300000 

PHP Indexed Array

PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0.

PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.

Definition

There are two ways to define indexed array:

1st way:

  1. $size=array(“Big”,”Medium”,”Short”);  

2nd way:

$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  

PHP Indexed Array Example

 

<?php  
$size=array("Big","Medium","Short");  
echo "Size: $size[0], $size[1] and $size[2]";  
?> 

Output:Size: Big, Medium and Short

<?php  
$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  
echo "Size: $size[0], $size[1] and $size[2]";  
?>  

Output:Size: Big, Medium and Short

Traversing PHP Indexed Array

We can easily traverse array in PHP using foreach loop. Let’s see a simple example to traverse all the elements of PHP array.

<?php  
$size=array("Big","Medium","Short");  
foreach( $size as $s )  
{  
  echo "Size is: $s<br />";  
}  
?>  

Output:

Size is: Big
Size is: Medium
Size is: Short

Count Length of PHP Indexed Array

PHP provides count() function which returns length of an array.

<?php  
$size=array("Big","Medium","Short");  
echo count($size);  
?>  

Output:

3

PHP Arrays

PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.


Advantage of PHP Array

Less Code: We don’t need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.


PHP Array Types

There are 3 types of array in PHP.

  1. Indexed Array
  2. Associative Array
  3. Multidimensional Array

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

  1. $season=array(“summer”,”winter”,”spring”,”autumn”);  

2nd way:

$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  

Example

<?php  
$season=array("summer","winter","spring","autumn");  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  

Output:

Season are: summer, winter, spring and autumn

<?php  
$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

  1. $salary=array(“Sonoo”=>”350000″,”John”=>”450000″,”Kartik”=>”200000”);  

2nd way:

$salary["Sonoo"]="350000";  
$salary["John"]="450000";  
$salary["Kartik"]="200000";  

Example

<?php    
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>    

Output:

Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

 

<?php    
$salary["Sonoo"]="350000";    
$salary["John"]="450000";    
$salary["Kartik"]="200000";    
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>   

Output:

Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

PHP Recursive Function

PHP also supports recursive function call like C/C++. In such case, we call current function within function. It is also known as recursion.

It is recommended to avoid recursive function call over 200 recursion level because it may smash the stack and may cause the termination of script.

Example 1: Printing number

   

<?php    
function display($number) {    
    if($number<=5){    
     echo "$number <br/>";    
     display($number+1);    
    }  
}    
    
display(1);    
?> 

Output:

1
2
3
4
5

Example 2 : Factorial Number

 

<?php    
function factorial($n)    
{    
    if ($n < 0)    
        return -1; /*Wrong value*/    
    if ($n == 0)    
        return 1; /*Terminating condition*/    
    return ($n * factorial ($n -1));    
}    
    
echo factorial(5);    
?>   

Output:

120

PHP Variable Length Argument Function

PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.

The 3 dot concept is implemented for variable length argument since PHP 5.6.

Let’s see a simple example of PHP variable length argument function.

<?php  
function add(...$numbers) {  
    $sum = 0;  
    foreach ($numbers as $n) {  
        $sum += $n;  
    }  
    return $sum;  
}  
  
echo add(1, 2, 3, 4);  
?>  

Output:10

PHP Functions

PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are thousands of built-in functions in PHP.

In PHP, we can define Conditional functionFunction within Function and Recursive function also.


Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages.

Less Code: It saves a lot of code because you don’t need to write the logic many times. By the use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application because every logic is divided in the form of functions.


PHP User-defined Functions

We can declare and call user-defined functions easily. Let’s see the syntax to declare user-defined functions.

Syntax

  

function functionname(){  
//code to be executed  
}

Note: Function name must be start with letter and underscore only like other labels in PHP. It can’t be start with numbers or special symbols.

PHP Functions Example

<?php  
function sayHello(){  
echo "Hello PHP Function";  
}  
sayHello();//calling function  
?>  

Output:Hello PHP Function

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length argument list.

  

<?php  
function sayHello($name){  
echo "Hello $name<br/>";  
}  
sayHello("Sonoo");  
sayHello("Vimal");  
sayHello("John");  
?>

Output:

Hello Sonoo
Hello Vimal
Hello John
<?php  
function sayHello($name,$age){  
echo "Hello $name, you are $age years old<br/>";  
}  
sayHello("Sonoo",27);  
sayHello("Vimal",29);  
sayHello("John",23);  
?>  

Output:

Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference

Value passed to the function doesn’t modify the actual value by default (call by value). But we can do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you need to use ampersand (&) symbol before the argument name.

<?php  
function adder(&$str2)  
{  
    $str2 .= 'Call By Reference';  
}  
$str = 'Hello ';  
adder($str);  
echo $str;  
?>  

Output:

Hello Call By Reference

PHP Function: Default Argument Value

We can specify a default argument value in function. While calling PHP function if you don’t specify any argument, it will take the default argument. Let’s see a simple example of using default argument value in PHP function.File: functiondefaultarg.php

<?php  
function sayHello($name="Sonoo"){  
echo "Hello $name<br/>";  
}  
sayHello("Rajesh");  
sayHello();//passing no value  
sayHello("John");  
?>  

Output:

Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value

Let’s see an example of PHP function that returns value.File: functiondefaultarg.php

<?php  
function cube($n){  
return $n*$n*$n;  
}  
echo "Cube of 3 is: ".cube(3);  
?>  

Output:

Cube of 3 is: 27

PHP While Loop

PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the body of loop.

It should be used if the number of iterations is not known.

The while loop is also called an Entry control loop because the condition is checked before entering the loop body. This means that first the condition is checked. If the condition is true, the block of code will be executed.

Syntax

while(condition){  
//code to be executed  
} 

Alternative Syntax

while(condition):  
//code to be executed  
  
endwhile;  

PHP While Loop Example

<?php    
$n=1;    
while($n<=10){    
echo "$n<br/>";    
$n++;    
}    
?> 

Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example

<?php    
$n=1;    
while($n<=10):    
echo "$n<br/>";    
$n++;    
endwhile;    
?>   

Output:

1
2
3
4
5
6
7
8
9
10

Example

Below is the example of printing alphabets using while loop.

<?php  
    $i = 'A';  
    while ($i < 'H') {  
        echo $i;  
        $i++;  
        echo "</br>";  
    }  
?>  

Output:

A
B
C
D
E
F
G

PHP Nested While Loop

We can use while loop inside another while loop in PHP, it is known as nested while loop.

In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

<?php    
$i=1;    
while($i<=3){    
$j=1;    
while($j<=3){    
echo "$i   $j<br/>";    
$j++;    
}    
$i++;    
}    
?> 

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP Infinite While Loop

If we pass TRUE in while loop, it will be an infinite loop.

Syntax

while(true) {    
//code to be executed    
}    

Example

<?php  
    while (true) {  
        echo "Hello protutorials!";  
        echo "</br>";  
    }  
?>  

Output:

Hello protutorials!
Hello protutorials!
Hello protutorials!
Hello protutorials!
.
.
.
.
.
Hello protutorials!
Hello protutorials!

PHP For Loop

PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how many times you want to execute a block of code.

It allows users to put all the loop related statements in one place. See in the syntax given below:

Syntax

  1. for(initialization; condition; increment/decrement){  
  2. //code to be executed  
  3. }  

Parameters

The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following meanings:

initialization – Initialize the loop counter value. The initial value of the for loop is done only once. This parameter is optional.

condition – Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.

Increment/decrement – It increments or decrements the value of the variable.

Example

<?php    
for($n=1;$n<=10;$n++){    
echo "$n<br/>";    
}    
?>

Output:

1
2
3
4
5
6
7
8
9
10

Example

All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don’t pass parameters, it will execute infinite.

<?php  
    $i = 1;  
    //infinite loop  
    for (;;) {  
        echo $i++;  
        echo "</br>";  
    }  
?>  

Output:

1
2
3
4
.
.
.

Example

Below is the example of printing numbers from 1 to 9 in four different ways using for loop.

<?php  
    /* example 1 */  
  
    for ($i = 1; $i <= 9; $i++) {  
    echo $i;  
    }  
    echo "</br>";  
      
    /* example 2 */  
  
    for ($i = 1; ; $i++) {  
        if ($i > 9) {  
            break;  
        }  
        echo $i;  
    }  
    echo "</br>";  
      
    /* example 3 */  
  
    $i = 1;  
    for (; ; ) {  
        if ($i > 9) {  
            break;  
        }  
        echo $i;  
        $i++;  
    }  
    echo "</br>";  
      
    /* example 4 */  
  
    for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);  
?> 

Output:

123456789
123456789
123456789
123456789

PHP Nested For Loop

We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop executes only when the outer for loop condition is found true.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

<?php    
for($i=1;$i<=3;$i++){    
for($j=1;$j<=3;$j++){    
echo "$i   $j<br/>";    
}    
}    
?>

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP For Each Loop

PHP for each loop is used to traverse array elements.

Syntax

foreach( $array as $var ){  
 //code to be executed  
}  
?>  

Example

<?php  
$season=array("summer","winter","spring","autumn");  
foreach( $season as $arr ){  
  echo "Season is: $arr<br />";  
}  
?>  

Output:

Season is: summer
Season is: winter
Season is: spring
Season is: autumn