Php Install

There are many ways to install PHP on your computer machine.

Install PHP through Xampp software

Xampp is a Windows,MacOs and Linux web development environment. It is the most famous in the market. when you install this software then many software is installed automatically like PHP, Apache, MariaDB, and Perl.
kindly go to the below URL to install the package

https://www.apachefriends.org/download.html

Install PHP through Wamp software

WampServer is a Windows web development environment. It allows you to create web applications with Apache2, PHP, and MySQL. You can download it through the below link.

https://www.wampserver.com/en/

Install package one by one separately

Install packages through a command in Linux.

Install Apache


sudo apt update
sudo apt install apache2

Install PHP


sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql

Install MySql


sudo apt-get install mysql-server

PHP Editor

You can try the code on the editor.


<!DOCTYPE html>
<html>
<head>
<title>PHP Editor</title>
</head>
<body>
<h1>Welcome PHP Editor</h1>
<?php 
$msg='PHP code must be write into php tag and click on the "Run" button to view the result.';
echo $msg;
?>
</body>
</html>

Try Php Editor

Php Syntax

Php is a scripting language and it is used to create dynamic webpages. It is very easy to learn. Now times more than 70% of websites are built in PHP. every PHP file has .php extension.

Syntax:-


<?php 

?>

Example:- you have to print Hello Php


<?php 
print 'Hello Php';
?>
Hello Php

Try it on PHP Editor

HTML Embedding in php file

You can embedded html code into PHP file


<HTML>
<HEAD> 
This is a sample. 
</HEAD>
<BODY>
Hello Removeload.com
<?php 
print "Hi, how are you?";
?>
</BODY>
</HTML>

How to enable PHP short tag?

You can enable php short tag through php.ini file. firstly open the php.ini file after that short_open_tag=on.


short_open_tag=on

Now, write the PHP code

Syntax:-


<?

?>

Example:- you have to print Hello Friends


<?
print 'Hello Friends';
?>
Hello Friends

Php foreach loop

foreach loop an easy way to iterate over arrays.It is used only on arrays and objects to iterate the value.

Syntax:- this syntax represent only each iteration value.


foreach (iterable_expression as $value)
 statement

Example:-
Suppose, You have game_arr variable which has 4 game and now iterate the game through foreach loop.


<?php
$game_arr=array('Hockey','Cricket','Tennis','Football');
foreach($game_arr as $game_name){

	echo $game_name.'<br/>';
}
?>
Hockey
Cricket
Tennis
Football

Try it Yourself

Syntax:- this syntax represent current element’s key to the $key variable on each iteration.


foreach (iterable_expression as $key => $value)
    statement

Example:-
Suppose, You have game_arr variable which has 4 game and now iterate the game through foreach loop.


<?php
$game=array('Hockey','Cricket','Tennis','Football');
foreach($game as $key => $game_name){

	echo $game_name.' is on array position '.$key.'<br/>';;
}
?>
Hockey is on array position 0
Cricket is on array position 1
Tennis is on array position 2
Football is on array position 3

Try it Yourself

Php do while loop

Do While loop works same as other programming languages. In the Do while loop, The only difference is that a do while loop checks its truth expression before ending each iteration. Basically, this kind of loop makes sure that your statement will run at least once, regardless of the truth expression’s value.

Syntax:-


do
statement
while
(expression);

Example:-


<?php
$x=1;
do{
print $x.'<br/>';
$x++;
} while($x<5)

?>
1
2
3
4

Try it Yourself

Php While loop

While loop works same the other programming language. In the while loop, If the expression’s result is true, the loop will run all the statements inside it. If the result is false, however, the loop will end and pass the program control to the statements after it.

Syntax:-


while (expression)
statement

Example:-


<?php
$i=1;
while($i<5){

	print $i."<br/>";
	$i++;
}
?>
1
2
3
4

Try it Yourself

Php for loop

The for loop of PHP is similar to that of the C language. It has three parameters. first parameter is used to initialize the variable value, second parameter is used to define the condition and third parameter is used to increase or decrease the variable value.

Syntax:-


for (start_expression; condition_expression; increment_or_decrement_expression)

Example1:- Suppose, You have a variable $x and that has value 1 and you increase the $x value until $x value will be 4.


<?php
for ($x = 1; $x < 5; $x++) {
print $x ."<br/>";
}
?>
1
2
3
4

Try it Yourself

Example2:- Suppose, You have a variable $x and that has a value 5 and you decrease the $x value until $x value will be 2


<?php
for ($x = 5; $x>1; $x--) {
print $x ."<br/>";
}
?>
5
4
3
2

Try it Yourself

Php switch statement

Php switch statements to replace complicated if-elseif statements. Switch statements compare an expression against all of the possible entries inside their body. If they don’t find an exact match, the program will run the “default” clause and ignore the rest of the statement. In PHP, you may use a “break” statement to terminate the code’s execution and pass the control to the succeeding scripts.

Syntax:-


<?php
switch (expression) {
case expression:
statement1
case expression:
statement2
...
default:
statementn
}
?>

Example:-


<?php
$game = "Cricket";
switch ($game) {
  case "Cricket":
    echo "Sachin belongs to cricket!";
    break;
  case "Hockey":
    echo "Dhayan Chand belongs to Hockey";
    break;
  case "Tennis":
    echo "Mahesh Bhupathi belongs to Tennis!";
    break;
  default:
    echo "Players neither belongs to Cricket, Hockey, nor Tennis!";
}
?>
Output:- Sachin belongs to cricket!

Try it Yourself

Php if else condition

In PHP, if-else is used for conditional statements. there are 3 types to use if-else condition.

1) if condition:- “if” condition will be executed when “if” statement is true.

Syntax:-


<?php
if(conditional_expression)
{

}
?>

Example:- Suppose, You have $x variable and that has value 100 and now you create the condition.


<?php
$x=100;
if($x>90)
{

 echo 'condition is passed';

}
?>
condition is passed

Try it Yourself

2) if else condition:- “if” condition will be executed when “if” statement is true otherwise false condition will be executed.

Syntax:-


<?php
if(conditional_expression)
{

}else{
}
?>

Example:- Suppose, You have $x variable and that has value 80 and now you create the condition.


<?php
$x=80;
if($x>90)
{

 echo 'condition is passed';

}else{

 echo 'condition is failed';

}
?>
condition is failed

Try it Yourself

3) if elseif condition:- “if” condition will be executed when “if” statement is true otherwise check else if condition.

Syntax:-


<?php
if(conditional_expression1)
{

}elseif(conditional_expression2)
{

}else{

}
?>

Example:- Suppose, You have $x variable and that has value 80 and now you create the condition.


<?php
$x=80;
if($x>90)
{

 echo 'x value is greater than 90';

}elseif($x>70 && $x<90){

 echo 'x value is between 70 to 90';

}else{
echo 'condition does not match';
}
?>
x value is between 70 to 90

Try it Yourself

PHP Operator

The PHP language supports basically two types of operators.
1) Unary operator
2) Binary operator

1) Unary Operator:- The Unary Operator works only on single operands.

Increment and Decrement Operator

a) Increment Operator:- There are two types of Operator.

(i) Post-Increment:- It represents ++ sign after variable like $varable++. This is called Post-increment operator. It returns the current value of the variable and increases it by 1.


<?php
$x=100;
echo $x++;
?>
Output:- 100

Try it Yourself

(ii) Pre-Increment:- It represents ++ sign before the variable like ++$varable This is called Pre-increment operator. It increases the value of the variable by 1 and returns the resulting value..


<?php
$x=100;
echo ++$x;
?>
Output:- 101

Try it Yourself

b) Decrement Operator:- There are two types of operator.

Post-Decrement:- It represents — sign after variable like $varable–. This is called Post-Decrement operator. It returns the current value of the variable and decrease it by 1.


<?php
$x=100;
echo $x--;
?>
Output:- 100

Try it Yourself

Pre-Decrement:- It represents — sign before the variable like –$varable This is called Pre-Decrement operator. It decrease the value of the variable by 1 and returns the resulting value.


<?php
$x=100;
echo --$x;
?>
Output:- 99

Try it Yourself

Cast Operator

PHP Language has six cast operators that you can use to force type conversions. You should place the operator on the left-side of the operand.

(array) – This operator converts values into an array.


<?php
$x=100;
$y= (array)$x;
print_r($y);
?>
Output:- Array ( [0] => 100 )

Try it Yourself

(int) or (integer) – This operator convert values into integers.


<?php
$x="100";
$y= (int)$x;
echo $y;
?>
Output:- 100

Try it Yourself

(string) – This operator converts values into a string.


<?php
$x=100;
$y= (string)$x;
echo $y;
?>
Output:- “100”

Try it Yourself

(object) – This operator convert values into the object.


<?php
$x=100;
$y= (object)$x;
print_r($y);
?>
Output:- stdClass Object ( [scalar] => 100 )

Try it Yourself

(real), (float) or (double) – This operator allows you to convert values from any data type into floating-point values.


<?php
$x="100";
$y= (double)$x;
echo gettype($y);
?>
Output:- double

Try it Yourself

(bool) or (boolean) – Use this operator to convert any value into its Boolean form.


<?php
$x="100";
$y= (bool)$x;
echo gettype($y);
?>
Output:- boolean

Try it Yourself

The Negation Operators

PHP language support 2 types of Negation Operators.

a) Logical Negation Operator:- It represents through ! operator. It will give you true if the operand’s value is false. If the value is true, on the other hand, this operator will give you false.


<?php
$x=100;
if(!$x){

echo 'x variable does not exist';

}else{

echo 'x variable exists';

}
?>
Output:- x variable exists

Try it Yourself

b) Bitwise Negation operator:- It represents through “~” operator. It replaces 0 with 1, and vice versa.

2) Binary Operator:- A binary operator requires two Operands.

The Numeric Operators

There are 5 numeric operator.

(i) Addition Operator:- It represents “+” sign between two operands and return the sum value.


<?php
$x=100;
$y=40;
$z=$x+$y;
echo $z;
?>
Output:- 140

Try it Yourself

(ii) Subtract Operator:- It represents “-“ sign between two operands and returns the subtraction value from left operands to right operands.


<?php
$x=100;
$y=40;
$z=$x-$y;
echo $z;
?>
Output:- 60

Try it Yourself

(iii) Multiplication Operator:- It represents “*” sign between two operands and returns the multiply value.


<?php
$x=100;
$y=40;
$z=$x*$y;
echo $z;
?>
Output:- 4000

Try it Yourself

(iv) Division Operator:- It represents the “/” sign between two operands and It divides the value of the left-hand operand by that of the right-hand operand and returns the quotient.


<?php
$x=100;
$y=40;
$z=$x/$y;
echo $z;
?>
Output:- 2.5

Try it Yourself

(v) Modulus Operator:- It represents the “%” sign between two operands and divides the value of the left-hand operand by that of the right-hand operand and returns the remainder.


<?php
$x=100;
$y=40;
$z=$x%$y;
echo $z;
?>
Output:- 20

Try it Yourself

Assignment Operator

An assignment operator allows you to assign values to your variables. Assignment operators are used with numeric values.

= operator:- It is used to assign the value.


x=2;

+= operator:- it is basically used to addition between two operands.


x+=y like x=x+y;

Try it Yourself

-= operator:- it is basically used to subtraction between two operands.


x-=y like x=x-y;

Try it Yourself

*= operator:- it is basically used to multiplication between two operands.


x*=y like x=x*y;

Try it Yourself

/= operator:- it is basically used to division between two operands.


x/=y like x=x/y;

Try it Yourself

%= operator:- it is basically used to modulas between two operands.


x%=y like x=x%y;

Try it Yourself

Comparison Operator

You can use these operators to compare the values of two operands.

“==” Operator – This operator checks whether the operands have equal values. It will give you true if the values are equal.

example,


$x == $y

Try it Yourself

“!=” Operator – if the value of the operand are not equal. For instance,


100 != 40

evaluates to true.
Try it Yourself

“>” Operator – this refers to greater than the operator. you can check whether the value of the left-hand operand is greater than that of the right-hand operand.
Try it Yourself

“<" Operator - this refers to less-than operator. you can check whether the value of the left-hand operand is less than that of the right-hand operand.
Try it Yourself

“<=" Operator - this refers to less than or equal operator. It will give you true if the value of the left-hand operand is less than or equal to the second operand.

Try it Yourself

“>=” Operator – this refers to greater than or equal operator. It will give you true if the value of the left-hand operand is greater than or equal to the second operand.

example, $x >= $y
Try it Yourself

Logical Operator

PHP represents some Logical operator.

(i) Logical AND:- this represents through “&&”. It will give you true if the both operands are true.


$x && $y

Try it Yourself

(ii) Logical OR:- this represents through “||”. It will give you true if the one operands is true.


$x || $y 

Try it Yourself

(iii) Logical XOR:- this represents through “xor”. It will give you true if only one of the operands is true. Thus, you will get false if both of the operands are true or false.
Try it Yourself

Concatenation Operator

this operator is used to concate the two or more strings. It works only for strings value.
It converts non-string operands to string operands.


<?php
$emp_age = 23;
print "Employee age is " . $emp_age;
?>
Employee age is 23

Try it Yourself

PHP Conditional Assignment Operator

Ternary Operator(?:)- this operator is used to check conditions.

Syntax:-


conditional_statement ? first_expression : second_expression

The “?” operator evaluates the result of “conditional_statement” If the result is true, the
operator will return the value of “first_expression”. If the result is false, the operator will
give you the value of “second_expression”.

Example:-


<?php
$x=10;
echo ($x==10) ? 'even number': 'odd number';
?>
Output:- even number

Try it Yourself

coalescing operator (??)- PHP7 introduce coalescing operator. The Null coalescing operator returns its first operand if it exists and is not NULL otherwise, it returns its second operand.


<?php
$employee='John';
$employee_name = $employee ?? 'employee not exists';
/** This is equivalent to: **/
$employee_name = isset($employee) ? $employee : 'employee not exists';
?>
Output:- John

Try it Yourself

Php Constants

PHP Constant is a variable and you can use it anywhere in the code.
A constant variable doesn’t need a dollar($) sign before its name.
You can not alter a PHP constant once you have assigned its value.
You can create Php constant variable through the define() keyword.

How to create constant variable?

You can create a constant variable through the define() keyword. It has three parameters.

Syntax:-


<?php
define(NAME_OF_CONSTANT,VALUE,CASE-INSENSITIVE);
?>

NAME_OF_CONSTANT:- It represents the name of the constant variable. NAME_OF_CONSTANT that consists of letters and numbers. Constant variable name should be in upparcase format. It is mandatory.

VALUE:- It represents constant variable value. It is mandatory.

CASE-INSENSITIVE:- It represents case-sensitive false or true. By-default repesents false. It is optional.

Example:- Suppose, You create a constant variable REMOVELOAD_ACADEMY and put the value Removeload Academy is a free e-learning tutorial Portal after that call it through the constant variable name.


<?php
define('REMOVELOAD_ACADEMY','Removeload Academy is a free e-learning tutorial Portal');
echo REMOVELOAD_ACADEMY;
?>
Output:- Removeload Academy is a free e-learning tutorial Portal

Try it Yourself

Example:- Now, you define the CASE-INSENSITIVE true.


<?php
define('REMOVELOAD_ACADEMY','Removeload Academy is a free e-learning tutorial Portal',true);
echo removeload_academy;
?>
Output:- Removeload Academy is a free e-learning tutorial Portal

Try it Yourself

PHP Constant Array

In PHP7, you can create constant variable value into an array format.

Example:-


<?php
define('SOFTWARE_COMPANIES',array('TCS','HCL','Infosys','Oracle'));
echo SOFTWARE_COMPANIES[0]; //TCS
echo SOFTWARE_COMPANIES[1]; //HCL
echo SOFTWARE_COMPANIES[2]; //Infosys
echo SOFTWARE_COMPANIES[3]; //Oracle
?>

Try it Yourself

Php Datatype

Php support 8 types of datatype. PHP variables behave according to the type of data they hold.

Integer
Float
String
Array
Object
Boolean
Null
Resources

Php Integer

Php Integer is a whole number means it is not decimal number.
Range of Integer variable value are from -2,147,483,648 to 2,147,483,647
Integer variable value can be positive or negative.

Example:- Suppose you have $num variable which has value 2500 and you can use var_dump() method to get datatype and variable value.


<?php
$num=2500;
var_dump($num);
?>
Output:- int(2500)

Try it Yourself

Php Float

Php floating-point number is also called real number. A floating number has decimal point and it has positive and negative sign before number.

Example:- Suppose you have $num variable which has value 2.5 and you can use var_dump() method to get datatype and variable value.


<?php
$num=2.5;
var_dump($num);
?>
Output:- float(2.5)

Try it Yourself

Php String

Php strings are sequences of characters (i.e. letters and numbers)
While adding a string value to your PHP code through single quotes or double quotes.

Single Quotes – This is the simplest option that you can use when creating a string.
Write your string between a pair of quotes.

Example:- Suppose you have $employee_name variable which has value John Taylor.


<?php
$employee_name='John Taylor';
echo $employee_name;
?>
Output:- John Taylor

Try it Yourself

Double Quotes – double quotes strings can hold the variable value.
Example:- Suppose you have $employee_name variable which has value John Taylor.


<?php
$employee_name='John Taylor';
$employee_greetings ="Hello $employee_name";
echo $employee_greetings;
?>
Output:- Hello John Taylor

Try it Yourself

Php Array

PHP array is a group of key and value pairs. array index can be integer or string. Phy array has multiple value into single variable.

Declare Php Array through array()
Syntax:-


<?php
$var=array();
?>

Example:- Suppose, You create a employee_name array which has multiple values and get the value.


<?php
$employee_name=array('John','Rom','Mathew');
echo $employee_name[0];  // John
echo $employee_name[1];  // Rom
echo $employee_name[2];  // Mathew
?>

Try it Yourself

Declare key and value into the array()
Suppose, You create a employee array which has keys and values and get the values based on the array key.


<?php
$employee=array('name'=>'John','age'=>5, 'designation'=>'Software Engineer');
// get the array element value
echo $employee['name'];
echo $employee['age'];
echo $employee['designation'];
?>

Try it Yourself

Php Object

Php Object is an instance of a class.
An entity that has state and behavior is known as an object like a car, cycle, table, chair, etc.

Example:- Suppose you create Employee class which has property name $empname and function display_empname() and after that create object through new keyword.


<?php
class Employee {
    public $empname;
    function display_empname($empname) {
        return $empname;
    }
 
}
$emp_obj = new Employee;
echo $emp_obj -> display_empname('John');
?>
Output:- John

Try it Yourself

Php Boolean

Php boolean is used in conditional codes like (if, loops, etc.) statements. You should know that data types are often converted to Boolean during runtime.

Php boolean has two state
1) true or 1
2) false or 0

Example:-


<?php
$a=true;
or
$b= false;
?>

Php NULL

Php NULL data type can only have a NULL value. You can use NULL datatype as a empty variables.

The isset() operator gives false output for Null values if the variable being checked exists while you use other data type then isset() will give you true if the variable exists .

Example:-


<?php
$x=NULL;
if(isset($x)){
echo 'success';

}else{
 echo 'fail';
}

?>
Output:- fail

Try it Yourself

Php Resource

PHP resource a special type of data. It represents an extension resource of PHP such as an open file.
You can not handle a resource variable directly.
You can simply send it to different functions that can interact with the involved resource.

Php Super Global Variable

Variables that you can access from any part of your code is called global variable. In Php, you can not create global variable but PHP use some variable that act like as super global variable.

There are some superglobal variables

$_ENV[]:-This is an array that contains environment variables.


<?php
print_r($_ENV);
?>

$_GET[]:- This is an array and holds all of the GET variables gathered from the user’s web browser.


<?php
print_r($_GET);
?>

$_POST[] – This is an array and holds all of the POST variables gathered from the user’s web browser.


<?php
print_r($_POST);
?>

$_SERVER[] – This kind of array holds the values of web-server variables.


<?php
print_r($_SERVER)
?>

It will show all web server variables value like HTTP_HOST, HTTP_CONNECTION, etc.

Php empty() method

PHP empty() method is used to check the variable has value or not. It gives output in a boolean value. if the variable empty then the output will be true or 1 and if the variable is not empty then the output will be false or 0.

Syntax:- to check the variable is empty


<?php
empty($variable_name)
?>

Example:- Suppose, You have employee_name variable which has empty value and now you want to check employee_name variable is empty or not.


<?php
$employee_name="";
if(empty($employee_name))
{
echo 'employee is empty';
}

?>
Output:- employee is empty

Try it Yourself

Php unset() method

Php unset() method is used to delete the variable. when you unset the variable then variable is deleted and it release the occupied memory by the variable.
unset() method is used to delete the array element and object property also.

Syntax:-


<?php
unset($variable_name);
?>

Example:- Suppose, You have an employee_name variable and you unset this variable and after that print, this variable then shows the Undefined variable: employee_name.


<?php
$employee_name="John";
unset($employee_name);
echo $employee_name;
?>
Notice: Undefined variable: employee_name

Try it Yourself

Delete the Array element through unset() method

If you want to delete the array then use unset() method.

Syntax:-


<?php
unset($array_element);
?>

Example:- Suppose, You have an emp_arr array and you want to unset this array element which is on zero position then use unset() method.


<?php
$emp_arr=array("John","Tom","Mathew");
unset($emp_arr[0]);
print_r($emp_arr);
?>
Output:- Array ( [1] => Tom [2] => Mathew )

Try it Yourself

Php isset() method

PHP isset() method is used to check the variable or array or object’s property is exists or not. It gives output in a boolean value. if the variable or array element or object’s property exists then the output will be true or 1 and if the variable or array or object’s property does not exist then the output will be false or 0.

Syntax:- to check the variable


<?php
isset($variable_name)
?>

Example:- Suppose, You have employee_name variable which has value John and now you want to check employee_name variable is exists or not.


<?php
$employee_name="John";
if(isset($employee_name))
{
echo $employee_name.' is exists';
}

?>
Output:- John is exists

Try it Yourself

Example2:- Suppose, You check employee_age exists or not


<?php
if(isset($employee_age))
{
echo $employee_age.' is exists';

}else{

echo 'employee age does not exist';

}

?>
Output:- employee age does not exist

Try it Yourself

Php Variable

Php variable is different from other programming languages like Java, .Net, c, c++, etc because PHP variable is weakly typed and you can change the datatype of the variable whenever you want. You can use PHP variable without prior declaration.
Php variable is introduced through the dollar($) sign.


<?php
$name='John';
?>

Display the varible value through echo or print

echo and print is used to display the value.

Example:-


<?php
$name='John';
echo $name;
?>

Try it Yourself

Output:- John

Example:-


<?php
$name='John';
print $name;
?>
Output:- John

Try it Yourself

Declare PHP variable

You can declare variables through the string, underscore, and numbers but the first character should not be a number.

Example:- Suppose, You declare variable through $name variable.


<?php
$name='John';
echo $name;
?>
Output:-John

Example:- Suppose, You declare variable which is start through underscore (_) through $_name variable.


<?php
$_name='John';
echo $_name;
?>
Output:-John

Example:- Suppose, You declare variable $1_name then it will show error when you echo this variable


<?php
$1_name='John'; 
echo $1_name;
?>
Ouput:-syntax error, unexpected ‘1’ (T_LNUMBER), expecting variable (T_VARIABLE)

Weakly Datatype

Php variable datatype is weakly datatype.

Example:- Suppose, you declare string value into name variable after that you defined numeric value into name variable then it will show last update value.


<?php
$name="John";
$name= 25;
echo $name
?>
Output:-25

Try it Yourself

Indirect Reference

PHP allows you to access a variable using indirect reference. There are no limits regarding the number of indirect references that you can use.


<?php
$car = 'TataNexon'; 
$TataNexon = "This is developed by Tata Motors";
echo $$car;
?>
Output:- This is developed by Tata Motors

Try it Yourself

In the above example firstly execute $car variable and get the value TataNexon after that $TataNexon variable will execute and get the value This is developed by Tata Motors.

Php Comments

Developers use comments to describe the details of the code. In PHP there is three-way to describe the comments.

Shell Method

this method is used to single-line comment and it is used through # to comment the details.


<?php
# describe about code details
?>

Example:- Suppose, You created user_greetings function in the user file.


<?php

# user file

function user_greetings($name){

	return 'Hello '.$name;
}
echo user_greetings('John');
?>
Output:- Hello John

Try it Yourself

Single-line Comment

It is basically used for single-line comment and it works the same as the shell method. this method is copied from the c language.

Syntax:-


<?php
 // describe about code details
?>

Example:- Suppose, You created user_full_name function in the user file.


<?php
// get user full name function

function user_full_name($first_name,$last_name){

	return $first_name.' '.$last_name;
}

echo user_full_name('John','Taylor');
?>
Output:- John Taylor

Try it Yourself

Multi-line Comment

this method is used to comments for multiple lines. this method is copied from the c++ language.

Syntax:-


<?php
 /* 
describe 
about 
code details
*/
?>

Example:- Suppose, You created sum of nunbers in the user file and you defined multi-line comments for number1 and number2 .


<?php
/*
$number1=10
$number2=20;
*/
$number3=30;
$number4=40;

$sum_of_numbers=$number3+$number4;

echo $sum_of_numbers;
?>
Output:- 70

Try it Yourself

What is PHP

PHP stands for Hypertext Pre-processor. Php is a server-side scripting language. It is basically used for website development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994;

Syntax:-


<?php 

?>

Try it on PHP Editor
if short tag is enable in php.ini file

Syntax:-


<?

?>

Example:-


<?php
echo 'Hello Friends';
?>
Output:- Hello Friends

PHP Advantage

1) Easy to read and write code.
2) It is supported by a majority of Operating Systems like Solaris, UNIX, Windows, and Linux.
3) Easy database connectivity.
4) It is an Open source so there is no need to pay anything.

Important Framework:- There are lots of PHP framework famous in the market like Laravel, Codeigniter, CakePHP, Zend, Symphony, etc.

Important CMS:- There are lots of PHP CMS in the market.

Ecommerce CMS:- There are lots of E-commerce CMS in the Market But Magento is more famous than other

Blogging CMS:- WordPress is most famous in the world, there are 70% website used this CMS on the web.

Some Important website which is developed in PHP

1) Facebook
2) Wikipedia
3) Yahoo
4) Tumblr
5) WordPress
6) MailChimp
7) Flickr

Vulnerabilities

When we do coding then we should use some rules for coding, if we donot follow the standard rule then our site can be hack by hackers.
so beware of some Vulnerabilities.
(i) Cross Site Request Forgery(CSRF)
(ii) Cross Site Scripting(XSS)
(iii) Sql Injection
(iv) Password Management
(v) Session Management

Cross Site Request Forgery(CSRF)

Cross Site Request Forgery or CSRF is an attack that forces a malicious action to an innocent website.

A cross-site request forgery (CSRF) vulnerability occurs when:
1. A Web application uses session cookies.
2. The application acts on an HTTP request without verifying that the request was made with the user’s consent.

Imagine a Web application
that allows administrators to create new accounts by submitting this form:
[php]
<form method="POST" action="/new_user.php" name="usr_form">
Name of new user:
<input type="text" name=”username”>
Password for new user:
<input type="password" name="user_passwd">
<input type="submit" name="action" value="Create User">
</form>
[/php]

An attacker might set up a Web site with the following:

[php]
<form method="POST" action="http://www.example.com/new_user.php" name="usr_form">
<input type="hidden" name="username" value="hacker">
<input type="hidden" name="user_passwd" value="hacked">
</form>
<script>
document.usr_form.submit();
</script>
[/php]

If an administrator for example.com visits the malicious page while she has an active session on the site, she will unwittingly create an account for the attacker.This is a CSRF attack.

Recommendations:
Applications that use session cookies must include some piece of information in every form post that the back-end code can use to validate the provenance of the request.
Firstly create random value and put into session
$_SESSION[‘token’]=md5(uniqid(mt_rand(), true));
[php]
<form method="POST" action="/new_user.php" name="usr_form">
Name of new user:
<input type="text" name="username">
Password for new user:
<input type="password" name="user_passwd">
<input type="hidden" name="csrf" id="csrf" value="<?php echo $_SESSION[‘token’];?>" />
<input type="submit" name="action" value="Create User">
</form>
[/php]
Now newuser.php
[php]
if (isset($_POST[‘action’]) && $_REQUEST[‘csrf’] == $_SESSION[‘token’]) {
//put add user code here
}
[/php]

Cross Site Scripting

Sending unvalidated data to a web browser can result in the browser executing malicious code.

Cross site scripting (XSS) vulnerabilities occur when:

1. Data enters a web application through an untrusted source. In the case of Persistent (also known as Stored) XSS, the untrusted source is typically a database or other back-end datastore, while in the case of Reflected XSS it is typically a web request.

2. The data is included in dynamic content that is sent to a web user without being validated.

Recommendations:
When malicious data store in the database then we use htmlentities() or htmlspecialchars()
eg:-
[php]
$getSql = "select coursetypeId,coursetypeName from coursetype where deleteFlag=0 Order By coursetypeOrder";
$getSql_sth = $dbh -> prepare($getSql);
$getSql_sth -> execute();
while ($results = $getSql_sth -> fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
echo htmlentities($results[‘coursetypeId’]);
}
[/php]

Sql Injection

SQL injection errors occur when:
1. Data enters a program from an untrusted source.
2. The data is used to dynamically construct a SQL query.

Example 1: The following code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where the owner matches the user name of the currently-authenticated user.
[php]
$userName = $_POST[‘userName’];
$itemName = $_POST[‘itemName’];
$query = "SELECT * FROM items WHERE owner = ‘$userName’ AND itemname = ‘$itemName’;";
$result = mysql_query($query);
[/php]

If an attacker with the user name enters the string “name’ OR 1=1 for itemName, then the query becomes the following:
SELECT * FROM items WHERE owner = ‘John’ AND itemname = ‘name’ OR 1=1;
The addition of the OR 1=1 condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;

Example 2. If an attacker with the user name wiley enters the string “name’; DELETE FROM items; –” for itemName, then the query becomes the following two queries:
SELECT * FROM items WHERE owner = ‘John’ AND itemname = ‘name’; DELETE FROM items;

Recommendations:
(1) use mysql_real_escape_string function when we get the value from form.
eg. [php]
$username= mysql_real_escape_string($_POST[‘userName’]);
$itemName= mysql_real_escape_string($_POST[‘itemName’]);
[/php]

(2) use sql pdo query not simple query
[php]
$query = "SELECT * FROM items WHERE owner = ? AND itemname = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param($username,$itemName);
$stmt->execute();
[/php]

Password Management

there are some rules for password management
(1) Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.
so we should use autocomplete=”off”
eg:- <input type=”password” name=”pass” autocomplete=”off” />

(2) Password value must be md5 with salted.
[php]
<?php $_SESSION[‘salt’]=uniqid(mt_rand(), true);
md5( $_SESSION[‘salt’] . password );
?>
[/php]

Session Management

Session ID must be different to all pages.

Ques:- How to create session ID different to all pages.
Ans:-session ID is create different through session_regenerate_id(true) function.

eg:- in login.php
[php]
session_start();
session_regenerate_id(true);
$_SESSION[‘user_id’] =$results[‘uId’];
$_SESSION[‘uName’] = $results[‘uName’];
[/php]

write the code to all pages
[php]
session_start();
$sess_uid=$_SESSION[‘user_id’];
$sess_uname=$_SESSION[‘uName’];
unset($_SESSION[‘user_id’]);
unset($_SESSION[‘uName’]);
session_regenerate_id(true);
$_SESSION[‘user_id’]=$sess_uid;
$_SESSION[‘uName’]=$sess_uname;
[/php]

MySql Interview Questions

What is MySql?

MySQL is the most popular Open Source SQL database management system, is developed, distributed, and supported by Oracle Corporation.

Ques:-What is the default port for MySQL Server?
Ans:- The default port for MySQL server is 3306.

Database related interview question

Ques:- How to Create a database on the mysql server through query?
Ans:- create database databasename

Ques:- How to show all database on the mysql server through query?
Ans:- show databases

Ques:- How to delete a database from mysql server?
Ans:- drop database databasename

Table related interview question

Ques:- How to create table into mysql server?
Ans:- CREATE TABLE table_name (column_name column_type);
Example:- [php]
CREATE TABLE employee(name VARCHAR(20), address VARCHAR(20));
[/php]

Ques:- How To see all the tables from a database?
Ans:- show tables

Ques:-How to see table’s field formats or description of table?
Ans:- describe tablename

Ques:-How to delete a table?
Ans:- drop table tablename

Ques:-How you will Show all data from a table?
Ans:- SELECT * FROM tablename

Different between NOW() and CURRENT_DATE() in php

Now():- It is used to show current year,month,date with hours,minutes and seconds.

CURRENT_DATE():- It is used to show current year,month and date.

Difference between MyISAM and InnoDB

MySQL supports several storage engines that act as handlers for different table types.

MYISAM:
(i) MYISAM is the default MySQL storage engine.
(ii) MYISAM supports Table-level Locking.
(iii) MyISAM is faster than InnoDB.
(iv) MyISAM does not support foreign keys.

InnoDB:
(i) InnoDB is not default MySQL storage engine.
(ii) InnoDB supports Row-level Locking.
(iii) InnoDB is slower than MYISAM.
(iv) InnoDB supports foreign keys.

what is trigger and types of triggers in mysql?

A trigger is a stored program that are run automatically when a specified change operation (SQL INSERT, UPDATE, or DELETE statement) is performed on a specified table.

there are six type of triggers in mysql
(i) BEFORE INSERT
(ii) AFTER INSERT
(iii) BEFORE UPDATE
(iv) AFTER UPDATE
(v) BEFORE DELETE
(vi) AFTER DELETE

Difference between primary key, unique key and candidate key

Primary Key:- (i) It has unique value and it can’t accept null values.
(ii) We can have only one Primary key in a table.

Unique Key:- (i) It has unique value and it can accept only one null values.
(ii) We can have more than one unique key in a table.

Candidate Key:- candidate key full fill all the requirements of primary key which is not null and have unique records is a candidate for primary key. So thus type of key is known as candidate key. Every table must have at least one candidate key but at the same time can have several.

Salary related interview question

emp_salary

Ques:- Maximum salary of the employee?
Ans:- [php]
select max(salary) from employee;
[/php]

Output:- 4000

Ques:- Second highest Maximum salary of the employee?
Ans:- We can get through sub-query, limit etc.
(i) Through Sub-query
[php]
SELECT max(salary) FROM `employee` where salary<(select max(salary) from employee)
[/php]

Output:- 3000

(ii) Through Limit
[php]
SELECT salary FROM `employee` Order by salary desc limit 1,1
[/php]

Output:- 4000

In this eg. limit is not work correctly because, salary may be same more than one person so its not good for use, it can use if employee salary is unique.

if Interviewer ask, how many person get second highest salary or third highest salary or fourth highest salary then you can use simple query method

SELECT salary FROM `employee` emp_a where (n-1)= (select count(distinct(salary)) from employee emp_b where emp_b.salary>emp_a.salary)

where n is use for number of highest salary

if you want to get second highest salary then
[php]
SELECT salary FROM `employee` emp_a where (2-1)= (select count(distinct(salary)) from employee emp_b where emp_b.salary>emp_a.salary)
[/php]

Output:- 3000
3000

In this example 2 employee has second highest salary

if you want to get third highest salary then
[php]
SELECT salary FROM `employee` emp_a where (3-1)= (select count(distinct(salary)) from employee emp_b where emp_b.salary>emp_a.salary)
[/php]

Output:- 2000

What is MySql Join?

“JOIN” is an SQL keyword used to query data from two or more related tables.

Types of join:-
1) Inner Join
2) Left Join
3) Right Join
4) Full Join
5) Self Join

emp_location

Example:- In the above figure, it has two tables, (i) Employee (ii) location

(1) Inner Join:- It require that a row from the first table has a match in the second table based on the join conditions.
OR
An inner join of two tables gives the result of intersect of two tables.

Ques:- Please write a query fetch employee name with location record?
mysql->SELECT e.emp_name,l.location_name from employee e inner join location l on e.emp_id=l.emp_id
inner-join-output

(2) Left Join:- It returns all rows from the left table (employee), with the matching rows in the right table (location). The result is NULL in the right side when there is no match.

mysql->SELECT e.emp_name,l.location_name from employee e left join location l on e.emp_id=l.emp_id
left-join

(3) Right Join:- It returns all rows from the right table (location), with the matching rows in the left table (employee). The result is NULL in the left side when there is no match.
mysql->SELECT e.emp_name,l.location_name from employee e right join location l on e.emp_id=l.emp_id
right-join

(4) Full Join:- It returns all records in both tables regardless of any match. Where no match exists, the missing side will contain NULL.
OR
A full outer join will give you the union of employee and location table,
mysql->(SELECT e.emp_name,l.location_name from employee e left join location l on e.emp_id=l.emp_id) union (SELECT e.emp_name,l.location_name from employee e right join location l on e.emp_id=l.emp_id)
full-join

(5) Self Join:- SELF JOIN is used to join a table to itself using join statement.
Ques:- write a query, get the employee name with employee reporting officer name?

mysql->SELECT e1.emp_name,e2.emp_name as reporting_officer_name from employee e1 left join employee e2 on e1.emp_reporting_officer=e2.emp_id
self-join

What is Distinct operator in mysql?

Distinct operator is used when we want unique value in the column.

mysql> SELECT DISTINCT columnname FROM tablename

What is Order by in mysql?

When we want the value in ascending or descending order through the column then we use Order by operator

Note:- By default Order is ascending we can change into descending order.

mysql> SELECT col1,col2,col3,col4 FROM tablename ORDER BY col1 DESC;

mysql> SELECT col1,col2,col3,col4 FROM tablename ORDER BY col1 ASC;

What is count operator in mysql?

count operator is use for count the row in the table.

mysql> SELECT COUNT(*) FROM tablename;

What is Like Operator in mysql?

LIKE operator in mysql, is used in a WHERE clause to search for a specified pattern in a column.

Wildcard characters are used with the SQL LIKE operator.
(i) % :- A substitute for zero or more characters.
(ii) _ :- A substitute for a single character.

emp

In this above figure, we have employee table which has three fields emp_id, emp_name, emp_reporting_officer.

Example:- (i) Write a query, get the all employee which start from “emp”

mysql->SELECT emp_id, emp_name FROM `employee` where emp_name like “emp%”
like-operator

Example:- (ii) Write a query, get the all employee which ending from “A”

mysql->SELECT emp_id, emp_name FROM `employee` where emp_name like “%A”
like-operator2

Example:- (ii) Write a query, get the all employee which starting with any character, followed by “mpC”

mysql->SELECT emp_id, emp_name FROM `employee` where emp_name like ‘_mpC’
like_operator3

Php Interview Questions

We have covered PHP interview questions in an easy way so that any fresher or experienced developer gets information from these questions. we define each and every topic with an example so that any reader understand easily.

Q1: What is Php?

PHP stands for Hypertext Preprocessor. PHP is a server-side scripting language that is used to develop dynamic websites. Php is an open-source technology so you can free download through the internet.

Q2: Difference between php4 and php5?

php5 is upgrade version of php4 and php5 improved object orientated programming features.

Q3: How to retrieve the data in the result set?

There is four methods to retrieve the data in the result set of MySQL using PHP.
(i) mysql_fetch_row():- this function fetches one row from a result-set and returns it as an enumerated array.

(ii) mysql_fetch_array():- this function Fetch a result row as an associative array, a numeric array, or both.

(iii) mysql_fetch_assoc():- this function Fetch a result row as an associative array.

(iv) mysql_fetch_object():- this function Fetch a result row as an as an object.

Q4: How to submit form without a submit button?

This is very simple because we can use through javascript function.
[php]<script>
document.form.submit();
</script>
[/php]

Q5: What is session?

Ans:- A session is a way to store information (in variables) to be used across multiple pages.
sessions are stored on the server.

Q6: How to create a session?

Ans:- We can create session through session_start() function

Q7: How to set a value in session?

Ans:- We set the value like this $_SESSION[$name]=$value;
Example:- [php]
<?php
$_SESSION[‘username’]=’John’;
?>
[/php]

Q8: How to remove data from session?

Ans:- We can remove data through unset function.
Example:- [php]
<?php
unset($_SESSION[‘username’]);
?>
[/php]

Q9: How to get the value of current session id?

Ans:- session_id() returns the session id for the current session.
Example:- [php]
<?php
session_id();
?>
[/php]

Q10: How to change session id on the page?

Ans:- We can change session id through session_regenerate_id(true) function.
Example:- [php]
<?php
session_regenerate_id(true);
?>
[/php]

Q11: How to destroy all session data?

Ans:- We can destroy all session data through session_destroy(void) or session_unset(void); function.
Example:- [php]
<?php
session_destroy();
or
session_unset();
?>
[/php]

Q12: What is the default session time in php?

Ans:- The default session time in php is until closing of browser.

Q13: What is cookie?

Ans:- Cookies works on client side and it is stored on the user’s browser.

Q14: What is the meaning of a Persistent Cookie?

Ans:- A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.

Q15: How to set cookies in PHP?

Ans:- We can set cookie through setcookie($cookie_name,$cookie_value,$time) function.
Example:- [php]
<?php
setcookie("username", "John", time()+3600);
?>
[/php]

Q16: How to retrieve cookies value in PHP?

Ans:- We can retrieve cookie through $_COOKIE[$cookie_name].
Example:- [php]
<?php
echo $_COOKIE[‘username’]; //output:-John
?>
[/php]

Q17: How to remove cookie in PHP?

Ans:- We can remove cookie through set the expiration date in the past.
Example:- [php]
<?php
setcookie("username", "", time()-3600);
?>
[/php]

Q18: What is Server?

$_SERVER is an array containing information such as headers, paths, and script locations.

Q19: How to get IP address of client?

Ans:- We can get through
[php]
$_SERVER[‘REMOTE_ADDR’]
[/php]

Q20: How to get previous reference page?

Ans:- We can get through
[php]
$_SERVER[‘HTTP_REFERER’]
[/php]

Q21: How to get browser property?

Ans:- We can get through
[php]
$_SERVER[‘HTTP_USER_AGENT’]
[/php]

Q22: How to get server name?

Ans:- We can get through
[php]
$_SERVER[‘SERVER_NAME’]
[/php]

Q23: Differences between?

1) echo and print
2) include(), include_once(), require(), require_once()
3) print_r() and var_dump()
4) unlink() and unset()
5) GET and POST method
6) Split and Explode
7) array_merge() and array_combine()
8) urlencode and urldecode
9) $variable and $$variable
10) strstr() and stristr()

Php Encapsulation

What is Php Encapsulation?

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
OR
Encapsulation means hiding the internal details of an object, i.e. how an object does something.
OR
Encapsulation is just when you want to hide stuffs into your object from the public
eg:- (i)capsule i.e. mixed of several medicines.
(ii) TV operation
It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the things in TV.
Example:-


<?php
class company { 
public function get_fresherPackage() {
return 0; 
} 
public function display_fresherPackage() {
echo $this->get_fresherPackage();
}

}
class TCS extends company {
public function get_fresherPackage() {
return 'TCS provide 3.2 Lakh per annum';
}

}
class Oracle extends company {
public function get_fresherPackage() {
return 'Oracle provide 4.2 Lakh per annum';
}

}

$com_Obj = new company;
$com_Obj -> display_fresherPackage();

$tcs_Obj = new TCS;
$tcs_Obj -> display_fresherPackage();

$oracle_Obj = new Oracle;
$oracle_Obj ->display_fresherPackage();
?>

Output:- 0
TCS provide 3.2 Lakh per annum
Oracle provide 4.2 Lakh per annum

In the above example, we create an object of the class company, TCS, Oracle, and call the function display_fresherPackage() and it is showing the results.

TCS and Oracle class object is understandable but company class object is meaningless because which company showing the fresher package.

But if we want this method should not call by the company object then we create this method as a protected instead of public (So this is a part of Encapsulation because hide the function display_fresherPackage for class company object ).
Example:-


<?php
class company {
public function get_fresherPackage() {
return 0;
}
protected function display_fresherPackage() {
echo $this->get_fresherPackage();
}

}
class TCS extends company {
public function get_fresherPackage() {
return 'TCS provide 3.2 Lakh per annum';
}

}
class Oracle extends company {
public function get_fresherPackage() {
return 'Oracle provide 4.2 Lakh per annum';
}

}
$com_Obj = new company;
$com_Obj -> display_fresherPackage();

$tcs_Obj = new TCS;
$tcs_Obj -> display_fresherPackage();

$oracle_Obj = new Oracle;
$oracle_Obj -> display_fresherPackage();
?>
Call to protected method company::display_fresherPackage()

Php Abstract Class

What is Abstraction?

Abstraction is process of hiding the implementation details and showing only the functionality.it shows only important things to the user and hides the internal details.
Example:-
When you start a car then you don’t know what is the mechanism work in this, that is called Abstraction.

Abstract Class

A class defined with abstract keyword, that class called Abstract Class. Abstract classes are those classes which can not be directly initialized.
OR
you can not create object of abstract classes.
Note:-
(i) abstract classes can hold abstract method and other method.
(ii) At least one abstract method must be in abstract class.
(iii) Abstract classes always created for inheritance purpose.
abstract class classname{
}

Example:- Abstract class and abstract method


<?php
abstract class Area {
	abstract public function getArea();
	public function showArea()
	{
	 echo $this->getArea();
	}
}
class rectangle extends Area
{
	public $length=100;
	public $width=50;   
	public function getArea()
	{
	 return 'Rectangle Area is '.($this->length)*($this->width);
	}
}
class triangle extends Area
{
	public $base=50;
	public $height=20;   
	public function getArea()
	{
	 return 'Triangle Area is '.($this->base)*($this->height)/2;
	}
}

$rec_obj = new rectangle;
$rec_obj -> showArea();

$tri_obj = new triangle;
$tri_obj -> showArea();
?>
Output:- Rectangle Area is 5000
Triangle Area is 500

Can not create object of abstract classes

If we create a object of the abstract class then show fatal error.


<?php
abstract class student {
	public $name = "john";
	public function student_name() {
		return $this -> name;
	}

}

$stu_obj = new student;
echo $stu_obj -> student_name();
?>
Output:- Fatal error: Cannot instantiate abstract class student

Abstract method

You can create any method abstract using keyword abstract.
Syntax:-
abstract function functionname(){
}

Note:-
(i)create abstract method either in abstract class or interface.
(ii) Abstract function must be declare in Abstract class and define in child class.
Example:-


<?php
abstract class country {
abstract public function country_name($cn);
}
class India extends country
{
public function country_name($cname)
{
echo 'Country name is '.$cname;
}	
}
$in_obj = new India;
$in_obj -> country_name('India');
?>
Output:- Country name is India

Why use Abstract class and method?

Many programmer thinks, what is purpose of use of abstract class and method.

Firstly without use abstract class program.

In the below example, when call Animals class and givemilk() method then show animals give us milk but all animals not give milk so it has no sense.


<?php
class Animals { 
    public function givemilk() {
    	//No sense 
       echo 'animals give us milk.'; 
    } 
 } 

class Cow extends Animals { 
    public function givemilk() {
    	echo 'Cow give us milk.';
   } 
} 

class Buffallo extends Animals { 
    public function givemilk() {
    	echo 'Buffallo give us milk.';
   } 
} 

$cow_obj=new Cow;
$cow_obj->givemilk();  

$buf_obj=new Buffallo;
$buf_obj->givemilk();  

$ani_obj=new Animals;
$ani_obj->givemilk(); 
?>
Output:- Cow give us milk.
Buffallo give us milk.
animals give us milk.

With Abstract class program

In the below eg. we declare abstract class Animals and it has abstract method givemilk(), you know abstract method is declare in the abstract class and define in the child class. so if we create a object of the abstract class and call the abstract method then show fatal error.


<?php
abstract class Animals { 
   abstract public function givemilk();
} 

class Cow extends Animals { 
    public function givemilk() {
    	echo 'Cow give us milk.';
   } 
} 

class Buffallo extends Animals { 
    public function givemilk() {
    	echo 'Buffallo give us milk.';
   } 
} 

$cow_obj=new Cow;
$cow_obj->givemilk();  

$buf_obj=new Buffallo;
$buf_obj->givemilk();   
?>
Output:- Cow give us milk.
Buffallo give us milk.

Php Interface

What is Php Interface?

An Interface is kind of like a class, although you can’t use it directly, classes must implement them.
An interface is a blueprint of a class.
Note:-
(i) In the interface, you will declare the functions.
(ii) The class implementing the interface must use the exact same method signatures as are defined in the interface.
(iii) All methods in the interface must be implemented within a class.
(iv) Classes may implement more than one interface if desired by separating each interface with a comma.
(v) It cannot be instantiated just like an abstract class.

Why use Interface
(i) It is used to achieve fully abstraction.
(ii) we can support the functionality of multiple inheritance.
(iii) It can be used to achieve loose coupling.

How to call Interface

when we call interface into class then we use implements and when we call interface into interface then we use extends.

Class call Interface-page0001

Example of Interface

In this eg. communication is a interface which is implement into french class and Indian class.


<?php
Interface communication {
public function language();
}
class French implements communication {
public function language() {
echo 'French person speak usually french language.';
}
}
class Indian implements communication {
public function language() {
echo 'Indian person speak usually hindi language.';
}
}

$fre_obj=new French;
$fre_obj->language(); 

$ind_obj=new Indian;
$ind_obj->language();
?>
Output:- French person speak usually french language.
French person speak usually hindi language.

Multiple inheritance by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

Multiple Inheritance-page0001

Example:-


<?php
Interface communication {
	public function language();
}

Interface country {
	public function people();
}

class Indian implements communication,country {

	public function people() {
		echo 'Indian people ';
	}

	public function language() {
		echo 'speak usually Hindi language.';
	}

}

$ind_obj = new Indian;
$ind_obj -> people();
$ind_obj -> language();
?>
Output:- Indian people speak usually Hindi language.

Multiple interface inheritance

A class implements interface but one interface extends another interface.

Example:-


<?php
Interface communication {
	public function language();
}

Interface country extends communication {
	public function people();
}

class French implements country {

	public function people() {
		echo 'French people ';
	}

	public function language() {
		echo 'speak usually french language.';
	}

}

$fre_obj = new French;
$fre_obj -> people();
$fre_obj -> language();
?>
Output:- French people speak usually french language.

Php static keyword

What is Php static keyword?

static keyword is mainly used for memory management.
static keyword can be variable, method and class.

static variable

Why use static variable?
You know static keyword is useful for memory management, if we want information of the employees of TCS then we need information (i) emp_id (ii)emp_name (iii)company_name (iv)emp_designation etc.
In this fields company_name is same for all employees so we can use static.
memory_manage_static_variable

Suppose there are 10000 employees in TCS, now all instance data members(variables) will get memory each time when object is created.All employee have its unique emp Id and empname, emp designation so instance data member is good.Here, Company refers to the common property of all objects.If we make it static,this field will get memory only once.


<?php 
class employee{
 public $emp_id;
 public $emp_name;
 public $emp_desg;
 public static $emp_comp="TCS";
 public function __construct($emp_id,$emp_name,$emp_desg){
 	$this->emp_id=$emp_id;
	$this->emp_name=$emp_name;
	$this->emp_desg=$emp_desg;
	 }
 public function emp_details()
 {
 echo $this->emp_id.' '.$this->emp_name.' '.$this->emp_desg.' '.self::$emp_comp;
 }
}
$emp1 = new employee(1,"john","prg");
$emp1->emp_details();
$emp2 = new employee(2,"tony","Sr.prg");
$emp2->emp_details();
?>
Output:- 1 john prg TCS
2 tony Sr.prg TCS

Without static variable counter program

In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won’t reflect to other objects. So each objects will have the value 1 in the count variable.
without_static_variable


<?php 
class employee {
	public $count = 1;
	public function __construct() {
		echo $this -> count++;
	}

}

$emp1 = new employee();
$emp2 = new employee();
?>
Output:- 1
1

With static variable counter program

static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
with-static-variable


<?php 
class employee {
	public static $count = 1;
	public function __construct() {
		echo self::$count++;
	}

}
$emp1 = new employee();
$emp2 = new employee();
?>
Output:- 1
2

static method

You can create your function or method static using static keyword. You can access all visible static methods for you using scope resolution operator(::) like in static variables.
Note:-
(i)A static method belongs to the class rather than object of a class.
(ii)A static method can be invoked without the need for creating an instance of a class.
(iii)static method can access static data member and can change the value of it.

Why use static method?
I have instantiable classes, but don’t need an entire object, just a particular method.
example
I have a class, which has dozen of method but i need only a single method then i define this method is static.


<?php 
class student {
	public $name;
	public $age;
	public static $rollno = 1125;

	public function stuInfo() {
		return $this -> name . " is " . $this -> age . " years old";
	}

	public static function ValidateRollNo($rollnumber) {
		if ($rollnumber == self::$rollno)
			return true;
		else
			return false;
	}

}

$rollnumber = 1125;
if (student::ValidateRollNo($rollnumber))
	echo "RollNumber is correct!";
else
	echo "RollNumber is NOT correct!";
?>
Output:- RollNumber is correct!

static method cannot access non-static variables and methods

Example:- In this eg. variable $name and $age which is not static, it is called into studentRecord() method which is static, when this program run it show error.


<?php 
class student {
	public $name="john";
	public $age="28";
	public static $rollno=1120;

	public function stuInfo() {
		return $this -> name . " is " . $this -> age . " years old";
	}

	public static function studentRecord() {
		echo $this->name;
		echo $this->age;
		echo $this->stuInfo();
	}

}
student::studentRecord();
?>
Output:- : Using $this when not in object

static method can access static data member and can change the value of it

Example:- In this eg. static method companyinfo() is accessing the static data member $comp_name and changed the value from TCS to Infosys.


<?php 
class employee {
	public $name = "john";
	public $age = "28";
	public static $comp_name = "TCS";

	public static function companyinfo() {
		self::$comp_name = "Infosys";
	}

	public function empInfo() {
		echo $this -> name . ' ' . $this -> age . ' ' . self::$comp_name;
	}

}

$emp_obj = new employee;
$emp_obj -> companyinfo();
$emp_obj -> empInfo();
?>
Output:- john 28 Infosys

Php Destructor

What is Php Destructor?

destructors – a function to be called when an object is deleted. PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++.
PHP calls destructors as soon as objects are no longer available, and the destructor function, __destruct(), takes no parameters.
void __destruct ( void )

why use destructor?
It gives the object an opportunity to prepare to be killed. This could mean manual cleanup, state persistence, etc.

example
you have create database object to communicate with database server after communicate with database server then you want to free database object through __destruct () method.


<?php 
function __construct()
{
  $this->link = mysql_connect($this->server.':'.$this->port, $this->username);
  if(!$this->link)
    die('Could not connect: '.mysql_error());

  if(!mysql_select_db($this->database, $this->link))
    die('Could not select database: '.mysql_error());
}    

function __destruct()
{
  if(mysql_close($this->link))
    $this->link = null; 
}
?>

Php Self keyword

What is Php Self keyword?

self keyword is used to access the current class itself.

Difference between self and this keyword.
(i) $this keyword to refer to the current object. self keyword to refer to the current class.
(ii) $this->member for non-static members, self::$member for static members.

self keyword refer to the current class

Example:- In this eg. we define two classes student and Year both has same method name whichClass(), Student class inherited in the Year class then we create a object and call the method sayClassName() which is defined in the Student class and it has self keyword. when this method call then it call current class method(whichClass()).


<?php 
class Student {
             public function whichClass() {
		echo "I am in MCA!";
	}
        /* This method has been changed to use the
	 self keyword instead of $this
	 */
        public function sayClassName() {
		self::whichClass();
	}
}

class Year extends Student {
        public function whichClass() {
		echo "I am in MCA first year!";
	}
}
$yearObj = new Year();
$yearObj -> sayClassName();
?>
Output:- I am in MCA!

this keyword refer to the current object

Example:- In this eg. we define two classes student and Year both has same method name whichClass(), Student class inherited in the Year class then we create a object and call the method sayClassName() which is defined in the Student class and it has this keyword. when this method call then it call current Object, method(whichClass()).


<?php 
class Student {
         public function whichClass() {
		echo "I am in MCA!";
	}
         /* This method has been changed to use the
	 $this keyword instead of self
	 */
         public function sayClassName() {
		$this->whichClass();
	}
}

class Year extends Student {
        public function whichClass() {
		echo "I am in MCA first year!";
	}
}
$yearObj = new Year();
$yearObj -> sayClassName();
?>
Output:- I am in MCA first year!

self keyword for static variable

this keyword is not work for static variable and method then we use self keyword.


<?php 
class stuClass {
public static $stu_name="ramesh";
public static $stu_rollno="Btech";

public static function display() {
echo self::$stu_name.' in '.self::$stu_rollno;
}
}
$sc=new stuClass;
$sc->display();
?>
Output:- ramesh in Btech

Php this keyword

What is this keyword in Php?

this is a reference variable that refers to the current object.
OR
The this keyword can be used to refer current class instance variable.

Understanding the problem without this keyword on method


<?php 
class MyClass {
	function MethodA() {
		echo "Hello";
	}

	function MethodB() {
		MethodA();
	}

}
$mc = new MyClass;
$mc -> MethodB();
?>
Fatal error: Call to undefined function MethodA()

With this keyword on the method


<?php 
class MyClass {
	function MethodA() {
		echo "Hello";
	}
    function MethodB() {
		$this->MethodA();
	}

}
$mc = new MyClass;
$mc -> MethodB();
?>
Output:- Hello

Understanding the problem without this keyword on variable


<?php 
class stuClass {
    public $stu_name="ramesh";
	public $stu_rollno="Btech";

    public function display() {
        echo $stu_name.' in '.$stu_rollno;
    }
}
$sc=new stuClass;
$sc->display();
?>
Notice: Undefined variable: stu_name
Notice: Undefined variable: stu_rollno

with this keyword on variable


<?php 
class stuClass {
    public $stu_name="ramesh";
	public $stu_rollno="Btech";

    public function display() {
        echo $this->stu_name.' in '.$this->stu_rollno;
    }
}
$sc=new stuClass;
$sc->display();
?>
Output:- ramesh in Btech

this keyword is not use for static variable and method

this keyword is not used for static variable and method in that situation we use self keyword which is define in the self keyword page.


<?php  
class stuClass {
    public static $stu_name="ramesh";
	public static $stu_rollno="Btech";

    public static function display() {
        echo $this->stu_name.' in '.$this->stu_rollno;
    }
}
$sc=new stuClass;
$sc->display();
?>
Fatal error: Using $this when not in object context

Php Constructor

What is Php Constructor?

(i) Php Constructor is a special type of method that is used to initialize the object.
(ii) The Constructor method is a special type of function called __construct within the class body.
(iii) To declare /create a constructor method, use the __construct name (begins with two underscore __).
(iv) This method is always “public” even if this attribute is not specified.
(v) The difference from the other functions is that a constructor method is automatically invoked when an object is created.Rules of creating Constructor
(i) The constructor name must be the same as its class name or use __construct.
(ii) The constructor must have no explicit return type.

Why use constructor?
It is usually used to automatically perform initializations such as property initializations.

Type of Constructor
(i) Default Constructor.
(ii) Parameterized Constructor.
Type-of-Constructor

Default Constructor

When create a object of the class then construct is called, if constructor has not parameter then it is called default constructor.


<?php 
class student  {
	//Define Constructor
	function __construct() {
       echo 'there are 90 students in the class';
    }
}
$stu = new student;
?>

OR


<?php 
class student  {
	//Define Constructor
	function student() {
       echo 'there are 90 students in the class';
    }
}
$stu = new student;
?>

Both Results are same.

Output:- there are 90 students in the class

Parameterized Constructor

If constructor has parameter is called parameterized constructor.


<?php 
class student {

    public $name; // this is initialization
    public $age;

    public function __construct($name,$age) {
      $this->name=$name;
	  $this->age=$age;
    }

    public function introduce() {
        echo "I'm {$this->name} and I'm {$this->age} years old";
    }

  
}
$stu = new student('John',27);
$stu->introduce();
?>
Output:- I’m John and I’m 27 years old

Parent constructor

Parent constructor are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.


<?php 
class MainClass {
   function __construct() {
       echo "In MainClass constructor!";
   }
}

class ChildClass extends MainClass {
   function __construct() {
       parent::__construct();
       echo "In ChildClass constructor!";
   }
}
$cc_obj=new ChildClass;
?>
Output:- In MainClass constructor!
In ChildClass constructor!

Final keyword

Final keyword in Php

if you declare class method as a Final then that method can not be override by the child class. Same as method if we declare class as a Final then that class can not be extended by child class.
Note:-
we can not declare variable as final (In Php we use const keyword instead of final keyword for variable but in Java we use final keyword for variable).

Syntax of final keyword for class:-
final class classname{
}

Syntax of final keyword for method:-
final function functionname(){
}

final class

A final class is a class that cannot be extended.
Example:- In this below eg. we create a two classes first class communication which is define as final and second class is Indian which is extended to communication class because communication is a final class so it can not be extended so system generate a compile error.


<?php 
final class communication {
public function language()
{
	return 'speak usually Hindi language.';
}
}
class Indian extends communication{
public function showInformation() {
	echo $this->language();
}
}
$ind_obj=new Indian;
$ind_obj->showInformation();
?>

the compiler will throw a compile error.

Output:- Fatal error: Class Indian may not inherit from final class (communication)

final method

A final method is a method that cannot be overridden.
Example:- In the below eg. language method is define as a final in the communication class and same method name is define in the Indian class so when call this method of the Indian class then system generate compile error.


<?php 
class communication {
	final public function language() {
		return 'speak usually Hindi language.';
	}
}
class Indian extends communication {

	public function language() {
		return 'speak usually English language.';
	}
        public function showInformation() {
		echo $this -> language();
	}
}

$ind_obj = new Indian;
$ind_obj -> showInformation();
?>

In this case the compiler causes a compile error.

Output:- Fatal error: Cannot override final method communication::language()

Is Final Method inherited?

Final method can be inherited but not override in child class.
Example:-


<?php 
class communication {
	final public function language() {
		return 'speak usually Hindi language.';
	}

}

class Indian extends communication {

	public function people() {
		return 'Indian people ';
	}

	public function showInformation() {
		echo $this -> people() . $this -> language();
	}

}

$ind_obj = new Indian;
$ind_obj -> showInformation();
?>
Output:- Indian people speak usually Hindi language.

Define keyword

Define keyword in Php

The define() function defines a constant.
Constants are much like variables, except for the following differences:
(i) Using define() INSIDE a class definition does not work..
(ii) A constant’s value cannot be changed after it is set.
(iii) Constants do not have a dollar sign ($) before them.
(iv) Constant values can only be strings and numbers.

Syntax:-
bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

Parameter
Description
$name
Required
$value
Required
$case_insensitive
Optional(false)

Note:-
(i) A valid constant name starts with a letter or underscore.
(ii) define keyword is used for global.

Example:-


<?php 
define("IMAGE_WIDTH", 400px);
echo IMAGE_WIDTH; // outputs:- 400px
echo IMAGE_width; // outputs:- "IMAGE_width" and issues a notice

define("IMAGE_WIDTH", 400px, true);
echo IMAGE_WIDTH; // outputs 400px
echo IMAGE_width; // outputs 400px
?>

Const keyword

Const keyword in Php

The const keyword defines a constant.
Constants are much like variables, except for the following differences:
(i) It is define must be inside the class.
(ii) A constant’s value cannot be changed after it is set.
(iii) Constants do not have a dollar sign ($) before them.

Note:-
(i) Inside the class then values of the constants can be get using self keyword.
(ii) accessing the value outside the class you have to use Scope Resolution Operator ::

Example:-


<?php 
class Employee {
const sift = "Office timming is 10am to 6pm.";
const company_name="Company name is TCS.";
function displaysift_timming()
{
echo self::sift;
}
}
echo Employee::company_name;
$emp_obj = new Employee;
$emp_obj->displaysift_timming();
?>
Output:- Company name is TCS.
Office timming is 10am to 6pm.

Php Object Cloning

What is Php Object Cloning?

Object cloning is the act of making a copy of an object.

Note:-
(i) If you will directly copy objects in PHP, then it will copy by reference, not by value.
(ii) if you will change main object data then copied objects will be affected. Also if you will change the value of the copied object then the main object value will be changed.
So if you want to create a copy of the object which should never be referenced to original object then you can take help of object cloning in php.

Simple Object Copy

Object Copy:-
If you will directly copy objects in php, then it will copy by reference, not by value.
Example:-


<?php
class student {
	public $stu_name = 'John';
}
 $stu_obj1 = new student;
 $stu_obj2 = $stu_obj1;
 $stu_obj2->stu_name="Tony";
 echo $stu_obj1->stu_name;
 echo $stu_obj2->stu_name;
?>
Output:- Tony
Tony

In this eg. object $stu_obj1 after copying it to $stu_obj2, we have changed its object value $stu_name to “Tony”, and then we have printed both object value and found that $stu_obj2 has changes made in $stu_obj1. This is one of the very useful when you want an object by reference. But when we need object copy by value, So to overcome with this limitation PHP has provided features of object cloning separately.

Object Copy with clone keyword

By default Object copy by reference but with the clone keyword we copy the object by value not by reference.
Example:-


<?php
class student {
	public $stu_name = 'John';
}
 $stu_obj1 = new student;
 $stu_obj2 = clone $stu_obj1;
 $stu_obj2->stu_name="Tony";
 echo $stu_obj1->stu_name;
 echo $stu_obj2->stu_name;
?>
Output:- John
Tony

In this eg. object $stu_obj1 after copy it to $stu_obj2 with clone keyword, we have changed its object value $stu_name to “Tony”, and then we have print both object value and found that $stu_obj2 has changed and stu_obj1 not changed.

Object cloning with magic method __clone

Magic method clone executes when object cloning is performed. As soon as php execute statement $stu_obj2 = clone $stu_obj1, __clone method invoked.


<?php
class student {
	public $stu_name = 'John';
	function __clone()
	{
		$this->stu_name='Tony';
	}
}
 $stu_obj1 = new student;
 $stu_obj2 = clone $stu_obj1;
 echo $stu_obj1->stu_name;
 echo $stu_obj2->stu_name;
?>
Output:- John
Tony

In this eg. object $stu_obj1 after copy it to $stu_obj2 with clone keyword, then _clone() method invoked, in this method we have changed $stu_name value to “Tony”, then we have print both object value and found that $stu_obj2 has changed and stu_obj1 not changed.

Note:- If you use clone keyword then you should use _clone() method also.

Php Object Serialization

What is Php Object Serialization?

Object serialization in PHP is very easy, and can be used for a variety of different purposes.

how to convert an object to a string, and vice-versa.
We can convert object to string through serialize() function and return string to object through unserialize() function.

Note:-(i) When serializing an object, PHP only stores the object’s current state, i.e. its property values. It does not serialize its methods.
(ii) When serializing an object, value store in byte-stream format.

serialization

Which situation we use serialization of the object:-
(i) Passing objects via fields in web forms.
(ii) Passing objects in URL query strings.
(iii) Storing object data in a text file, or in a single database field.

Example:-
In this eg. we have 2 files, in the first file we serialize the object of class student and in display.php we unserialize of the string variable which is created in student.php

(i) student.php


<?php
class student {
	public $stu_name = 'John';
	function display_name() {
		return $this -> stu_name;
	}

}

$stu_obj = new student;
$stu = serialize($stu_obj);
?>

(ii) display.php


<?php
include('student.php');
$stu_info = unserialize($stu);
echo $stu_info -> display_name();
?>
Output:- John

Php Magic method

What is Php Magic method?

PHP functions that start with a double underscore is called magic method.

Magic methods are always defined inside classes.

Note:- PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

The Magic Method are __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo()

__construct() method is already define on the constructor page.

__destruct() method is already define on the destructor page.

__call() and __callStatic() method is already define on the Method Overloading Page.

__clone() method is already define on the Object Cloning Page.

__toString() magic method

__toString() method is called whenever you try to use an object as a string context.

Note:- (i) __toString() must return a string value.
(ii) __toString() does not have parameter.
(iii) __toString() can not throw exception, results in fatal error.
(iv) if you call function in the __toString() that can throw exception.

Example:-


<?php
class student {
	public $stu_info = 'student information';
	function __toString() {
		return $this -> stu_info;
	}

}

$stu_obj = new student;
echo $stu_obj;
?>
Output:- student information

__get() magic method

The __get() method is called when code attempts to access a property or variable that is not accessible.

Note:- (i) It accepts one argument, which is the name of the property.
(ii) if variable not defined, then __get() method will be called both inside and outside of class context.

Why we use __get() method?

(i) Without __get() method Program:-
In the below eg. stu_college variable is not define in the class and we are calling this variable through object.
then show error.


<?php
class student {
	public $stu_name = 'John';
	
	function display_name()
	{
	 return $this->stu_name;
	}
}

$stu_obj = new student;
echo $stu_obj->stu_college;
?>

Output:- Undefined property: student::$stu_college

(ii) With __get() method Program:-
In this eg. we use __get() method which return field name which is not define in the class.


<?php
class student {
	public $stu_name = 'John';
	function display_name()
	{
	 return $this->stu_name;
	}
	function __get($field_name) {
		return $field_name;
	}
}

$stu_obj = new student;
echo $stu_obj->stu_college;
?>
Output:- stu_college

__set() magic method

The __set() method is called when code attempts to set a property or variable that is not accessible and property will be public.

Note:- (i) It accepts two arguments, which are the name of the property and the value.

Example:- In this program we set the value of the variable stu_college, which is not define in the class.


<?php
class student {
	public $stu_name = 'John';
	function __get($field_name) {
		return $field_name;
	}

	function __set($field_name, $field_value) {
		$this->$field_name=$field_value.' is my college';
	}
	function display()
	{
	 return $this->stu_college;
	}

}

$stu_obj = new student;
$stu_obj -> stu_college='IIT Delhi';
echo $stu_obj->stu_college;
?>
Output:- IIT Delhi is my college

__isset() magic method

It is invoked when isset() or empty() check non-existent or inaccessible class property.

Note:- __isset() method has only one parameter.

Firstly we read isset() method:-
It is a language construct that checks the initialization of variables or class properties:
eg:- $name=’John’;
var_dump(isset($name)); Output:- true
var_dump(isset($age)); Output:- false

Example of __isset():- In this eg. prop variable is not define in the class when call isset method then __isset() method invoked automatecally.


<?php
class Test
{
    public function __isset($name) {
        echo "Non-existent property '$name'";
    }
}

$obj = new Test;
var_dump(isset($obj->prop));
?>
Output:- Non-existent property ‘prop’
boolean false

__unset() magic method

__unset() is invoked when unset() is used on inaccessible properties. With the help of this method we can check for the undeclared variables in the code. We can also set appropriate error message while testing for variable names getting used in the Class.
Example:-


<?php
class student
{
	function __unset($variable_name)
	{
	echo $variable_name.' variabe is not define';
	}
}
$stu_obj =new student;
unset($stu_obj->stu_name);
?>
Output:- stu_name variabe is not define

Php Access Modifiers

PHP access modifiers are used to set access rights with PHP classes and their methods and variables.
There are 3 types of access modifiers:
(i) private
(ii) protected
(iii) public

Modifier Name With in Class Out Side Class Inheritance
Private

allow

disallow

disallow

Protected

allow

disallow

allow

Public

allow

allow

allow

private access modifiers

class variable or method with private access modifier can only be accessible inside the class. You can not access private method or variable from outside of your class.

Note:- Class can not be private.

Example:- In the below example we are accessing $stu_name variable and student_college_name method outside the class then show fatal error and if we are accessing both in the class then its working fine.


<?php 
class student {
	private $stu_name = 'John';
	private function student_college_name() {
		return 'HBIT Kanpur';
	}

	public function display_college_name() {
		return $this -> stu_name . ' is in ' . $this -> student_college_name();
	}

}

$stu_obj = new student;
echo $stu_obj -> stu_name; //Output:- Fatal error: Cannot access private property student::$stu_name
echo $stu_obj -> student_college_name(); //Output:- Fatal error: Call to private method student::student_college_name()
echo $stu_obj -> display_college_name(); //Output:- John is in HBIT Kanpur
?>

protected access modifiers

Class variable or method, that are set to be protected, can only be accessed inside the class and by its subclasses, in other words its class and sub classes.

Note:- Class can not be protected.

Example:- In the below example we are accessing $stu_name variable and student_college_name method outside the class then show fatal error and if we are accessing in the child class then its working fine.


<?php 
class student {
	protected $stu_name = 'John';
	protected function student_college_name() {
		return 'HBIT Kanpur';
	}

	
}
class student_information extends student
{
public function display_college_name() {
		return $this->stu_name . ' is in ' . $this->student_college_name();
}	
	
}
$stu_obj = new student;
$stuinfo_obj = new student_information;
echo $stu_obj -> stu_name; //Output:- Fatal error: Cannot access protected property student::$stu_name
echo $stu_obj -> student_college_name(); //Output:- Fatal error: Call to protected method student::student_college_name()
echo $stuinfo_obj -> display_college_name(); //Output:- John is in HBIT Kanpur
?>

public access modifiers

The public access modifier is accessible everywhere. If you define your class properties and methods as “public”, then it can be used anywhere in your PHP script.
Example:- In the below example we call the variable $stu_name and method student_college_name() out side of the class, then it is working fine.


<?php 
class student {
	public $stu_name = 'John';
	public function student_college_name() {
		return 'HBIT Kanpur';
	}
}
$stu_obj = new student;
echo $stu_obj -> stu_name; //Output:- John
echo $stu_obj -> student_college_name(); //Output:- HBIT Kanpur
?>

Php Autoload function

What is Php Autoload function?

__autoload() is a magic method, means it calls automatically when you try create an object of the class and if the PHP engine doesn’t find the class in the script it’ll try to call __autoload() magic method.
void __autoload ( string $classname )

Note:-(i) Autoload function does not return value.
(ii) class name and filename must be same.

Example:-


<?php
function __autoload($class_name) {
    include $class_name . '.php';
}

$obj1  = new MyClass1();
$obj2 = new MyClass2(); 
?>

What is the reason we use autoload function?

If we have 4 files
(a) tcs.php which has tcs information.
(b) oracle.php which oracle information.
(c) google.php which google information.
(d) companyinfo.php which has company information of all three company.

(i) first is tcs.php which has


<?php
class tcs{
public function which_type()
{
return 'TCS is a  consulting and business solutions company';
}
public function number_employees()
{
return 'Aproximate 3 lakh';
}
public function fresher_package_for_employee()
{
return '3.2 lakh per annum';
}
} 
?>

(ii) second is oracle.php


<?php
class oracle{
public function which_type()
{
return 'Oracle is a  database company';
}
public function number_employees()
{
return 'Aproximate 2 lakh';
}
public function fresher_package_for_employee()
{
return '5.2 lakh per annum';
}
}
?>

(iii) third is google.php


<?php
class google{
public function which_type()
{
return 'Google is a  search base company';
}
public function number_employees()
{
return 'Aproximate 2.5 lakh';
}
public function fresher_package_for_employee()
{
return '6.2 lakh per annum';
}
}
?>

In companyinfo.php we include all three files of company after that create a objects


<?php
include('tcs.php');
include('oracle.php');
include('google.php');

$tcs_obj= new tcs;
echo $tcs_obj->which_type(); 
echo $tcs_obj->number_employees(); 
echo $tcs_obj->fresher_package_for_employee();
?>
Output:- TCS is a consulting and business solutions
companyAproximate 3 lakh
3.2 lakh per annum

<?php
$orac_obj= new oracle;
echo $orac_obj->which_type();
echo $orac_obj->number_employees();
echo $orac_obj->fresher_package_for_employee();
?>
Output:- Oracle is a database company
Aproximate 2 lakh
5.2 lakh per annum

<?php
$google_obj= new google;
echo $google_obj->which_type();
echo $google_obj->number_employees();
echo $google_obj->fresher_package_for_employee();
?>
Output:- Google is a search base company
Aproximate 2.5 lakh
6.2 lakh per annum

In this example we include three files in the companyinfo.php but if want to include more than 20 files then it is a hard nut to crack to include the files..
So multiple include file problem, solve with the help of autoloading function.

so we used autoload function in the companyinfo.php


<?php
function __autoload($class_name)
{
include $class_name.'.php';
}
$tcs_obj= new tcs;
$orac_obj= new oracle;
$google_obj= new google;
?>

then create a object of the 3 classes then automatically include three files in this file.
autoload

Php Method overloading

What is Php method overloading?

Overloading in PHP provides means to dynamically create properties and methods.

“The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope”.

Note:- Php overloading is different than most object oriented languages.

In most object oriented languages
If a class has multiple methods by the same name but different parameters, it is known as Method Overloading.

Php Overloading has two types
(i) Method Overloading
(ii) Property Overloading

What is Method Overloading?

Magic method __call() or __callStatic() invoked when method called by class object is not available in class.
PHP method overloading allows function call in both object and static context. The related magic functions are,
(i) __call() is triggered when invoking inaccessible methods in an object context.
(ii) __callStatic() is triggered when invoking inaccessible methods in a static context.

public __call ( string $methodname , array $arguments )
public static __callStatic ( string $methodname , array $arguments )

Why we need __call or __callStatic method?
Example:-


<?php
class Employee {
	public $empname;
	public $age;
	public function empinfo($empname,$age) {
		echo $empname.' age is '.$age;
	}
	
}
$emp = new Employee;
$emp->companyname("TCS");
?>
Output:- Call to undefined method Employee::companyname()

In this eg. companyname() method is not define in the class then show fatal error.

Now with the help of __call() we can solve this error.


<?php
class Employee {
	public $empname;
	public $age;
	public function empinfo($empname,$age) {
		echo $empname.' age is '.$age;
	}
	public function __call($methodname,$arg)
	{
	echo $methodname.' is '.$arg[0];	
	}
	
}
$emp = new Employee;
$emp->companyname("TCS");
$emp->companylocation("New Delhi");
?>
Output:- companyname is TCS
companylocation is New Delhi

In this eg we don’t need to create function companyname() and companylocation(), with the help of __call() method we can do this.

__callStatic method
if we want to call static method which is not define in class then we use this method.
In this example we are using __callStatic() so we donot need to create a object of the class and call the method with :: operator.


<?php
class Employee {
	public $empname;
	public $age;
	public function empinfo($empname,$age) {
		echo $empname.' age is '.$age;
	}
	public static function __callStatic($methodname,$arg)
	{
	echo $methodname.' is '.$arg[0];	
	}
	
}
Employee::companyname("TCS");
Employee::companylocation("New Delhi");
?>
Output:- companyname is TCS
companylocation is New Delhi

Property Overloading method show in magic method page.

Php Method Overriding

What is Php Method Overriding?

If child class has the same method and parameter as declared in the parent class, it is known as method overriding.

Note:-(i) Method overriding is used for runtime polymorphism.
(ii) The static method of the class can not be overridden.

Example:-
In the below example, All companies give to a fresher package according to company rule. TCS gives 3.2 lakh per annum and Oracle gives 4.2 Lakh Package per annum and some small company does not give money to employees.
(i) fresherPackage method of TCS class override the method fresherPackage of company class.
(ii) fresherPackage method of Oracle class override the method fresherPackage of company class.


<?php
class company {
	public function fresherPackage() {
		echo 0;
	}
}
class TCS extends company{
	public function fresherPackage() {
		echo 'TCS provide 3.2 Lakh per annum.';
	}
}
class Oracle extends company{
	public function fresherPackage() {
		echo 'Oracle provide 4.2 Lakh per annum.';
	}
}
$tcs_Obj=new TCS;
$tcs_Obj->fresherPackage();

$oracle_Obj=new Oracle;
$oracle_Obj->fresherPackage();
?>
Output:- TCS provide 3.2 Lakh per annum.
Oracle provide 4.2 Lakh per annum.

Php Polymorphism

What is Php Polymorphism?

In general, polymorphism is the ability to appear in different forms. Technically, it is the ability to redefine methods for derived classes.

Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism means many forms.

Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

Why method polymorphism cannot be achieved?
The reason why polymorphism for methods is not possible in PHP is because you can have a method that accepts two parameters and call it by passing three parameters. This is because PHP is not strict and contains methods like func_num_args() and func_get_arg() to find the number of arguments passed and get a particular parameter.
Because PHP is not type strict and allows variable arguments, this is why method polymorphism is not possible.

Note:- polymorphism is possible with class methods. The basis of polymorphism is Inheritance and overridden methods.

In the below example method taste is different for different class, for Apple class, method show sweet taste and for class Orange method taste show sour so this is follow one name many form (Polymorphism).


<?php
interface fruit {
	public function taste();
}

class Apple implements fruit {
	public function taste() {
		return 'Apple taste is very sweet.';
	}

}

class Orange implements fruit {
	public function taste() {
		return 'Orange taste is very sour.';
	}

}


$app_Obj = new Apple;
echo $app_Obj -> taste();

$orange_Obj = new Orange;
echo $orange_Obj -> taste();
?>
Output:- Apple taste is very sweet.
Orange taste is very sour.

Php Inheritance

What is Php Inheritance?

inheritance is a mechanism, we can get all property and method of one class into another class.We can access all property and method through extends keyword.

Inheritance represents the IS-A relationship, also known as parent-child relationship.
What is IS-A relationship?
Is a Relationship-page0001

In this image, Narendra Modi is a Prime Minister, Narendra Modi is a Son and Narendra Modi is a politician. so this is called Is a relationship.

Why use Inheritance?
(i) For Code Reusability.
(ii) For Method Overriding.

Note:-
(i) The subclass inherits all of the public and protected methods from the parent class.
(ii) If a class extends another, then the parent class must be declared before the child class structure.

Syntax:-


<?php 
class childclass(or subclass) extends parentclass(or superclass)
{
}
?>

Example of Inheritance

In this example, generalManager class inherit the property and method of Empoyees class, officeTiming() Method of generalManager class, override the method of Empoyees class.


<?php 
class Empoyees {
	public function officeTiming(){
	echo 'Employee Office Timing is 10am to 7pm';
	}
}

class generalManager extends Empoyees {
    public function officeTiming(){
	echo 'General Manager Office Timing is 10am to 5pm';
	}

}

$gm_obj = new generalManager;
$gm_obj -> officeTiming();
?>
Output:- General Manager Office Timing is 10am to 5pm

Type of Inheritance

There are mainly 3 types of Inheritance in Php.
(i) Single Inheritance
(ii) Multilevel Inheritance
(iii) Hierarchical Inheritance

simple-Inheritance

two other inheritance used through Interface.
(iv) Multiple Inheritance
(v) Hybrid Inheritance

multiple-Inheritance

Why Multiple inheritance is not support Php language

Without Interface, Multiple inheritance is not support Php language.

Without Interface Multiple inheritance program
notsupport_multiple_inheritance

Output:- Compile time error, syntax error, unexpected ‘,’, expecting ‘{‘

Multiple inheritance By Interface
This section is explained in the Interface section.

Object and Class

What is Object

An entity that has state and behavior is known as an object eg:- as car,cycle,table,chair etc.
OR
Object is an instance of a class.
Note:- Object can be Physical or logical.
An object has three characteristics:
(i) state (ii) behavior (iii) identity
(i) state:- it is represent the data(value) of the object.
(ii) behavior:- it is represent the behavior(functionality) of the object.
(iii) identity:- it is represent object unique id.user can not see this id.
object

What is Class?

A class is the blueprint of the object. The class contains the methods and properties, or the characteristics of the object.

A class in php contain
(i) data member(variable)
(ii) method(function)
(iii) constructor
(iv) class and Interface

Syntax:-
class classname{
data-member(variable),
method(function)
}

Example of class:-
In this example we define a class employee, which has variable $empname and method name is display_empname()
and we create a object with new keyword.

class_employee


<?php 
class Employee {
	public $empname;
	function display_empname($empname) {
		return $empname;
	}

}
$emp_obj = new Employee;
echo $emp_obj -> display_empname('John');
?>
Output:- John

classification of class

Ques:- How to create a variable in the class?
Ans:- we can create a variable through public or var or protected or private.
class student{
var $stu_rollno;
public $stu_name;
protected $stu_marks;
private $stu_class;
}
Note:- var variable work as a public.

Ques:- what is the roll of Method in a class?
Ans:- It is used to expose behavior of an object.

Ques:- How to create a method in the class?
Ans:- we can create a method through public or protected or private.


<?php 
class student{
var $stu_rollno;
public $stu_name;
protected $stu_marks;
private $stu_class;
pubic function displayname($stu_name)
{
return $stu_name;
}
}
?>

Ques:- What is new keyword?
Ans:- The new keyword is used to allocate memory at runtime.

Ques:- How to create object or instance variable?
Ans:- with the help of new keyword, we create object(instance variable).


<?php 
class student{
var $stu_rollno;
public $stu_name;
protected $stu_marks;
private $stu_class;
pubic function displayname($stu_name)
{
return $stu_name;
}
}


$stu= new student;
echo $stu->displayname('Tony'); //Output is Tony
?>

Note:-$stu is a object in this program.

Ques:- How to call method of a class?
Ans:- there are many types for calling method
(i) If method is not static then
(a) call outside of the class then we use -> operator through object of the class.
eg:- $classobj->methodname;
in this eg $classobj is a object of the class.
(b) if method call inside the class then we use $this->
eg:- $this->methodname;

(ii) If method is static then
(a) call outside of the class then we use :: operator through the class.
eg:- classname::methodname;

(b) if method call inside the class then we use self::
eg:- self::methodname;

Ques:- How many create a object of a class?
Ans:- We can create multiple objects of a class.
Example:-
$stu1= new student;
$stu2= new student;

Memory allocation of object

The new keyword is used to allocate memory at runtime.
Example:-


<?php 
class Employee {
	public $empname;
	public $age;
	function empinfo($empname,$age) {
		echo $empname.' age is '.$age;
	}

}
$emp1 = new Employee;
$emp1 -> empinfo('John',22);
$emp2 = new Employee;
$emp2 -> empinfo('Tony',19);
?>
Output:- John age is 22
Tony age is 19

memory_allocation
In this figure, object gets the memory in Heap area and reference variable refers to the object allocated in the Heap memory area. Here, $emp1 and $emp2 both are reference variables that refer to the objects allocated in memory.

Difference between strstr() and stristr() in php

strstr() function

this function is used to find the first occurence of the string. this function is case-sensative. It has two parameters first parameter for the string and second parameter is used to define character which should be find from the string.


<?php
$email = 'john@tcs.com';
$email_data = strstr($email, 't');
echo $email_data;
?>
Output:- tcs.com

Try it Yourself

Suppose, the string has a duplicate character then find the first occurrence of the string.


<?php
$email = 'john_taylor@tcs.com';
$email_data = strstr($email, 't');
echo $email_data;
?>
Output:- taylor@tcs.com

Try it Yourself

Suppose, the string has a duplicate character then find the first occurrence of the string.

strstr() function is case-sensative


<?php
$email = 'john_Taylor@tcs.com';
$email_data = strstr($email, 't');
echo $email_data;
?>
Output:- tcs.com

Try it Yourself

stristr() function

this function works same as strstr() but it is a Case-insensitive manner.


<?php
$email = 'john_Taylor@tcs.com';
$email_data = stristr($email, 't');
echo $email_data;
?>
Output:- Taylor@tcs.com

Try it Yourself

Difference between $variable and $$variable

Indirect Reference used in the $$variable.
We explain the difference between $variable and $$variable through below example:-

Suppose, we create two variables.
(1) $variable which has value name.
(2) second variable name is the value of the first variable.


<?php
$variable = "name";
$name="John";
echo $$variable;
?>
Output: John

Work Flow of the above example


$$variable;

$$variable now process will work from right to left.


$name

after that output is


John

Difference between urlencode and urldecode

urlencode() function

This function is used to encode a string that can be used in a url. It encodes the same way posted data from the web page is encoded. It returns the encoded string.

Syntax:-


urlencode($string_value);

Example:-


<?php
$userName="John Taylor";
echo urlencode($userName);
?>
John+Taylor

Now, you can use urlencode() into URL


<?php
$userName="John Taylor";
echo '<a href="abc.php?uname='.urlencode($userName).'">URL</a>';
?>

urldecode() function

this function is used to decode the encoded string which is created by urlencode() function.
Syntax:-


urldecode($encoded_string_value);

Example:-


<?php
$userName="John Taylor";
echo $encodedUserName= urlencode($userName);  // John-Taylor
echo urldecode($encodedUserName);  // John Taylor
?>

Difference between array_merge() and array_combine()

array_merge()

this function is used to merge the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

Note:- If the input arrays have the same string keys, then the later value for that key will overwrite the previous one or if the arrays contain numeric keys, then the later value will not overwrite the original value and will be appended.


<?php 
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
Output:- Array( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4)

Try it Yourself

array_combine()

this function is used to create an array by using one array for keys and another for its values.


<?php 
$array1 = array("name","age","location");
$array2 = array("John", "27", "Delhi");
$result = array_combine($array1, $array2);
print_r($result);
?>
Output:- Array ( [name] => John [age] => 27 [location] => Delhi )

Try it Yourself

Difference between Split and Explode

split() and explode() functions are used to convert from string to array.

split() function

this function is removed from PHP7.

str_split() function

this function is used to convert from string to array.

Syntax:-


str_split ( string $string , int $length = 1 )

Note:- where int length is optional. If the optional length parameter is specified, the returned array will be broken down into chunks with each being length in length, otherwise, each chunk will be one character in length.

Example:- Suppose, you have a string and you want to split the string through str_split() function.


<?php 
$string="i am John";
$str_arr=str_split($string);
print_r($str_arr);
?>
Output:- Array ( [0] => i [1] => [2] => a [3] => m [4] => [5] => J [6] => o [7] => h [8] => n )

Try it Yourself


<?php 
$string="i am John";
$str_arr=str_split($string,2);
print_r($str_arr);
?>
Output:- Array ( [0] => i [1] => am [2] => J [3] => oh [4] => n )

Try it Yourself

explode() function

this function is used to convert from string to array using another string.

Example:- Suppose, you have a string and you split the string through “and” string.


<?php 
$string="John and Tony and Anna";
$str_arr=explode("and", $string);
print_r($str_arr);
?>
Output:- Array ( [0] => John [1] => Tony [2] => Anna )

Try it Yourself

Difference between GET and POST method?

Get methods are used to send data to the server.

GET method

(i) GET method data is sent through query string and display browser’s address field.

Example:-


$url="http://abc.com?email=john@abc.com&name=john"

Note:- in the above URL first query string add through ? mark after that add query string through & mark.

(ii) GET method is mostly used for submitting a small amount and less sensitive data.

How to get form field’s value through GET method

You can get form fields value through $_GET[] array method.
Example:-


$get_email=$_GET['email'];

POST method

(i) POST method data is sent by standard input (nothing shown in browser’s address field).
(ii) POST method is mostly used for submitting a large amount or sensitive data.

How to get form field’s value through POST method

You can get form fields value through $_POST[] array method.
Example:-


$post_email=$_POST['email'];

What are the types of Php error

There are many Types of errors
E_ERROR: A fatal error that causes script termination
E_WARNING: Run-time warning that does not cause script termination
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code
E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
E_CORE_WARNING: Warnings that occur during PHP’s initial startup
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
E_ALL: Catches all errors and warnings.

But basically we define 3 runtime errors.

(i) Notices: These are small, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although the default behavior can be changed.

(ii) Warnings: Warnings are more severe errors like attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

(iii) Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

Difference between unlink() and unset()

unlink() method

Php unlink() method is used to delete the given file or image from the file system.


<?php
$filename="/fakepath/abc.pdf"; 
unlink($filename);
?>

unset() method

Php unset() method is used to delete the variable. when you unset the variable then variable is deleted and it release the occupied memory by the variable.
unset() method is used to delete the array element and object property also.

Syntax:-


<?php
unset($variable_name);
?>

Example:- Suppose, You have an employee_name variable and you unset this variable and after that print, this variable then shows the Undefined variable: employee_name.


<?php
$employee_name="John";
unset($employee_name);
echo $employee_name;
?>
Notice: Undefined variable: employee_name

Try it Yourself

sort array in php without function

We can sort of array value through sort() function but if interviewer ask without this function create own function then its very easy.
Example:- array(1, 5, 6, 3, 2, 4, 7, 10, 8, 9) should be array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)


<?php 
$arr = array(1, 5, 6, 3, 2, 4, 7, 10, 8, 9);
$arr_count = count($arr);
for ($i = 1; $i < $arr_count; $i++) {
	for ($j = $i; $j > 0; $j--) {
		if ($arr[$j] < $arr[$j - 1]) {
			$temp = $arr[$j];
			$arr[$j] = $arr[$j - 1];
			$arr[$j - 1] = $temp;
		}
	}
}
?>
Output:- Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )

string reverse in php without using function

We can get string reverse through strrev() function. But string reverse should be without this function.
Example 1:- “John” should be “nhoJ”


<?php
$string = "John";
$arr_str = str_split($string);
$stlen = strlen($string);
for ($j = $stlen - 1; $j >= 0; $j--) {
	echo $arr_str[$j];
}
?>
Output:- nhoJ

Try it Yourself

Example 2:- If interviewer ask string reverse of words like “John working in TCS” should be “nhoJ gnikrow ni SCT”


<?php
$string="John working in TCS";
$str_into_arr = explode(" ", $string);
	$str_into_arr_count = count($str_into_arr);
	for ($i = 0; $i <= $str_into_arr_count - 1; $i++) {
		$arr_str = str_split($str_into_arr[$i]);
		$stlen = strlen($str_into_arr[$i]);
		for ($j = $stlen - 1; $j >= 0; $j--) {
			echo $arr_str[$j];
		}
		echo ' ';
	}
?>
Output:- nhoJ gnikrow ni SCT

Try it Yourself

Factorial Program in php

What is factorial?

Factorial is a part of mathematics. It is a positive number and it is multiplication of the all positive numbers and move to 1.


5!= 5*4*3*2*1
  = 120

Factorial program without any predefined method?

We can get factorial of any number


<?php 
function factorial($n)
{
	$fact=1;
	for($i=$n; $i>=1;$i--)
	{
	$fact=$fact*$i;	
	}
	return $fact;
}
echo factorial(4) //Output:- 24
echo factorial(5) //Output:- 120
?>

Try it Yourself

Factorial program through recursion

Factorial Program through recursion of any number


<?php 
function Recu_factorial($number)
{
	if($number==0)
	{
		return 1;
	}
	return $number * Recu_factorial($number - 1);
}

echo Recu_factorial(4); //Output:- 24
echo Recu_factorial(5); //Output:- 120
?>

Try it Yourself

Difference between print_r() and var_dump()

print_r() and var_dump() both are used for the array.

print_r()

It displays information about a variable in a way that’s readable by humans. array values will be presented in a format that shows keys and elements.
example:-


<?php 
$employees=array("Sachin","Rohit","Virat","M.S Dhoni");
print_r($employees);
?>
Output:- Array ( [0] => Sachin [1] => Rohit [2] => Virat [3] => M.S Dhoni )

Try it Yourself

var_dump()

It displays structured information about variables/expressions including its type and value.
example:-


<?php 
$employees=array("Sachin","Rohit","Virat","M.S Dhoni");
var_dump($employees);
?>
Output:-
array(4) { [0]=> string(6) “Sachin” [1]=> string(5) “Rohit” [2]=> string(5) “Virat” [3]=> string(9) “M.S Dhoni” }

Try it Yourself

Difference between include(), include_once(), require(), require_once()

Through functions, We can include the content of one PHP file into another PHP file before the server executes it.
(i) include()
(ii) require()

Example:- In this eg. we have 2 files
(i) topmenu.php
(ii) index.php
in this eg. topmenu file included in the index.php file

(i) topmenu.php


<div>
<div><a href="home">Home</a></div>
<div><a href="contactus">Contact Us</a></div>
</div>

(ii) index.php


<?php 
<html>
<body>
<div class="topmenu">
<?php include 'topmenu.php';?>
</div>
<div>Welcome to My site</div>
</body>
</html> 
?>

Difference between include() and require()
Include():- If an error occurs, the include() function generates a warning, but the script will continue execution.
require():- If an error occurs, the require() function generates a fatal error, and the script will stop.

include_once():- The include_once function is exactly the same as the include function except it will limit the file to be used once.

example:- I have include content.php file in the for loop and file will be include only one time. but loop will run four times.


<?php 
for($i=1;$i<5;$i++)
{
include_once('content.php');
}
?>

If we use include() function in the for loop and file will be include 4 times.


<?php 
for($i=1;$i<5;$i++)
{
include('content.php');
}
?>

Note:- require() and require_once() will be same work as a include() and include_once();

Ques:- Can we use include one file, more than one times in a PHP page?
Ans:- Yes we can use include one file, more than one times in any page.
Example:- We have 3 files (1) employee1.php (2) employee2.php (3) index.php
In employee1.php [php]

In employee2.php [php]

(1) We include employee1.php in the index.php 2 times.


<?php 
include('employee1.php');
include('employee1.php');
?>
Output:- this file show employee1 information
this file show employee1 information

(1) We include employee2.php in the index.php 2 times.


<?php 
include('employee2.php');
include('employee2.php');
?>
Output:- Fatal error: Cannot redeclare employee_details()

Difference between echo and print

echo and print both are used to output strings.

echo

(i) It accepts multiple arguments.


<?php 
$company_name='TCS';
echo 'company name is',$company_name; 
?>
Output:- company name is TCS

Note:- Comma is used for concatenation between the strings and we can pass multiple arguments through comma sign.

(ii) It has no return value.

(iii) echo is faster than print.

print

(i) It has only one argument.


<?php 
$company_name='TCS';
print 'company name is',$company_name;
?>
Output:- Parse error: syntax error

Note:- In this example, we passed two-argument so It shows a Parse error.

(ii) It has a return value.

(iii) the print is slower than an echo.