You are on page 1of 99

PHP | Constants

Last Updated : 09 Mar, 2018



Constants are either identifiers or simple names that can be assigned any fixed values.
They are similar to a variable except that they can never be changed. They remain
constant throughout the program and cannot be altered during execution. Once a
constant is defined, it cannot be undefined or redefined. Constant identifiers should be
written in upper case following the convention. By default, a constant is always case-
sensitive, unless mentioned. A constant name must never start with a number. It
always starts with a letter or underscores, followed by letter, numbers or underscore.
It should not contain any special characters except underscore, as mentioned.

Creating a PHP Constant

The define() function in PHP is used to create a constant as shown below:


Syntax:

define(name, value, case_insensitive)

The parameters are as follows:

 name: The name of the constant.


 value: The value to be stored in the constant.
 case_insensitive: Defines whether a constant is case insensitive. By default this value is False,
i.e., case sensitive.

Example:

<?php

// This creates a case-sensitive constant


define("WELCOME", "GeeksforGeeks");
echo WELCOME, "\n";

// This creates a case-insensitive constant


define("HELLO", "GeeksforGeeks", true);
echo hello;

?>

Output:

GeeksforGeeks
GeeksforGeeks
constant() function

Instead of using the echo statement ,there is an another way to print constants using
the constant() function.

Syntax

constant(name)

Example:

<?php

define("WELCOME", "GeeksforGeeks!!!");

echo WELCOME, "\n";

echo constant("WELCOME");
// same as previous

?>

Output:

GeeksforGeeks!!!
GeeksforGeeks!!!

Constants are Global: By default, constants are automatically global, and can be
used throughout the script, accessible inside and outside of any function.
Example:

<?php

define("WELCOME", "GeeksforGeeks");

function testGlobal() {
echo WELCOME;
}

testGlobal();

?>
GeeksforGeeks

Constants vs Variables

 A constant, once defined can never be undefined but a variable can be easily undefined.
 There is no need to use dollar sign($) before constants during assignment but while declaring
variables we use a dollar sign.
 A constant can only be defined using a define() function and not by any simple assignment.
 Constants dont need to follow any variable scoping rules and can be defined anywhere.
PHP Constant Class
Last Updated : 05 Jan, 2021



The const keyword is used to declare a class constant. A constant is unchangeable


once it is declared. The constant class declared inside the class definition. The class
constant is case-sensitive. However, it is recommended to name the constants in all
uppercase letters. Constant differ from normal variables as no $ (dollar sign) is used.
The default visibility of class constants is public. Class constants are useful when you
need to declare some constant data (which does not change) within a class.

There are two ways to access class constant:

1. Outside the Class: The class constant is accessed by using the class name followed by the
scope resolution operator (::) followed by the constant name.

Example:

<?php

class code{

// Declare const class


const Greetings = "Welcome to geeksforgeeks";
}

// Access const class


echo code::Greetings
?>

Output:

Welcome to geeksforgeeks

2. Inside the Class: It can be accessed by using the self keyword followed by the
scope resolution operator(::) followed by the constant name.

Example:

<?php

class code{

// Declare const class


const Greetings = "Welcome to geeksforgeeks";
public function welcome(){
echo self::Greetings;
}
}

// Access const class


$val = new code();
$val->welcome();

?>

Output:

Welcome to geeksforgeeks

PHP Defining Constants


Last Updated : 23 Feb, 2023



In a production-level code, it is very important to keep the information as either


variables or constants rather than using them explicitly. A PHP constant is nothing but
an identifier for a simple value that tends not to change over time(such as the domain
name of a website eg. www.geeksforgeeks.org). It is ideal to keep all the constants in
a single PHP script so that maintenance is made easier. A valid constant name must
start with an alphabet or underscore and requires no ‘$’. It is to be noted, constants are
irrespective of their scope i.e constants are automatic of global scope. In order to
create a constant in PHP, we must use the define() method.

Syntax:

bool define(identifier, value, case-insensitivity)

Parameters: The function has two required parameters and one optional parameter.

 identifier: Specifies the name to be assigned to the constant.


 value: Specifies the value to be assigned to the constant.
 case-insensitivity(Optional): Specifies whether the constant identifier should be case-
insensitive. By default, it is set to false i.e. case-sensitive.

Return Type: This method returns TRUE on success and FALSE on Failure.

Note: From PHP 8.0, the constants defined with the help of the define() function may
be case-insensitive.

Below are some examples to illustrate the working of the define() function in PHP.
Example 1: Below program illustrates defining case-insensitive constants.

<?php

// Case-insensitive constants
define("Constant","Hello Geeks!",TRUE);
echo constant;
echo Constant;
?>

Output:

Hello Geeks! // Case Insensitive thus value is echoed


Hello Geeks!

Example 2: Below program illustrates defining case-sensitive constants.

<?php

// Case-sensitive constant
define("Constant","Hello Geeks!");
echo constant;
echo Constant;
?>

Output:

constant // Case Sensitive thus value not echoed


Hello Geeks!

The PHP compiler will also throw a warning for the above program along with the
output as “PHP Notice: Use of undefined constant constant- assumed ‘constant’ in
line 5”.

Summary:

 Constants are identifiers that can be assigned values(string, boolean, array, integer, float, or
NULL) that generally don’t change over time.
 Constants are irrespective of the scope and always populate the global scope.
 define() method is used to define constants.
 The defined() method is used to check if a constant is defined.
 The constant() method is used to return the value of a constant and NULL if not the constant
is not defined.

PHP | Magic Constants


Last Updated : 17 Aug, 2021



Magic constants: Magic constants are the predefined constants in PHP which is used
on the basis of their use. These constants are created by various extensions. There are
nine magic constant in the PHP and all of the constant resolved at the compile-time,
not like the regular constant which is resolved at run time. There are eight magic
constants that start and end with double underscores (__).
All the constants are listed below with the example code:

1. __line__: This magic constant return the current line number of the file. If you use
this magic constant in your program file somewhere then this constant will display the
line number during compile time.

Syntax:

.__line__

Example:

<?php

echo "The Line number is : ". __line__;

?>

Output:

The Line number is : 3

2. __file__: This magic constant return the full path of the executed file with the name
of the file.

Syntax:

.__file__

Example:

<?php

echo "The file name is : ". __file__;

?>

Output:

The file name is : /home/3d27a639c57aaed9efa5880e613bc273.php

3. __dir__: This magic constant return the directory of the executed file.
Syntax:

.__dir__

Example:

<?php

echo "The directory is : ". __dir__;

?>

Output:

The directory is : /home

4. __function__: This magic constant return the name of the function where this
magic constant is included.

Syntax:

.__function__

Example:

<?php
function Geeks(){
echo "The function name is : ". __function__;
}
Geeks();
?>

Output:

The function name is : Geeks

5. __class__: This magic constant return the name of the class where this magic
constant is included.

Syntax:

__class__

Example:

<?php
class Geeks
{
public function getClassName(){
return __class__;
}
}
$obj = new Geeks();
echo $obj->getClassName();
?>

Output:

Geeks

6. __method__: This magic constant return the method name where this magic
constant is included.

Syntax:

__method__

Example:

<?php
class Company
{
public function GeeksforGeeks(){
return __method__;
}
}
$obj = new Company();
echo $obj->GeeksforGeeks();
?>

Output:

Company::GeeksforGeeks

7. __namespace__: This magic constant return the current namespace where this
magic constant is included.

Syntax:

__namespace__

Example:

<?php
namespace GeeksforGeeks;

class Company {
public function gfg() {
return __namespace__;
}
}

$obj = new Company();


echo $obj->gfg();

?>

Output:

GeeksforGeeks

8. __trait__: This magic constant return the trait name where this magic constant is
included.

Syntax:

__trait__

Example:

<?php
trait GeeksforGeeks{
function gfg(){
echo __trait__;
}
}
class Company{
use GeeksforGeeks;
}
$a = new Company;
$a->gfg();
?>

Output:

GeeksforGeeks

9. ClassName::class: This magic constant return the fully qualified class name.

Syntax:

ClassName::class

Example:

<?php

namespace Computer_Sciecnec_Portal;
class Geeks{ }

echo Geeks::class;//Classname::class
?>

Output:

Computer_Sciecnec_Portal\Geeks

PHP Operators
Last Updated : 19 Dec, 2021



In this article, we will see how to use the operators in PHP, & various available
operators along with understanding their implementation through the examples.

Operators are used to performing operations on some values. In other words, we can
describe operators as something that takes some values, performs some operation on
them, and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an
operator. It takes two values 1 and 2, performs an addition operation on them to give
3.

Just like any other programming language, PHP also supports various types of
operations like arithmetic operations(addition, subtraction, etc), logical
operations(AND, OR etc), Increment/Decrement Operations, etc. Thus, PHP provides
us with many operators to perform such operations on various operands or variables,
or values. These operators are nothing but symbols needed to perform operations of
various types. Given below are the various groups of operators:

 Arithmetic Operators
 Logical or Relational Operators
 Comparison Operators
 Conditional or Ternary Operators
 Assignment Operators
 Spaceship Operators (Introduced in PHP 7)
 Array Operators
 Increment/Decrement Operators
 String Operators

Let us now learn about each of these operators in detail.

Arithmetic Operators:

The arithmetic operators are used to perform simple mathematical operations like
addition, subtraction, multiplication, etc. Below is the list of arithmetic operators
along with their syntax and operations in PHP.
Operator Name Syntax Operation
+ Addition $x + $y Sum the operands
– Subtraction $x – $y Differences the operands
* Multiplication $x * $y Product of the operands
/ Division $x / $y The quotient of the operands
** Exponentiation $x ** $y $x raised to the power $y
% Modulus $x % $y The remainder of the operands

Note: The exponentiation has been introduced in PHP 5.6.

Example: This example explains the arithmetic operator in PHP.

<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n";

if ($x == 50 or $y == 20)
echo "or Success \n";

if ($x == 50 xor $y == 20)


echo "xor Success \n";

if ($x == 50 && $y == 30)


echo "&& Success \n";

if ($x == 50 || $y == 20)
echo "|| Success \n";

if (!$z)
echo "! Success \n";
?>

Output:

33
25
116
7.25
1

Logical or Relational Operators:

These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or
cannot be met so the result of a conditional statement can either be true or false. Here
are the logical operators along with their syntax and operations in PHP.
Operator Name Syntax Operation
Logical $x and True if both the operands are true else
and
AND $y false
Logical True if either of the operands is true
or $x or $y
OR else false
Logical $x xor True if either of the operands is true and
xor
XOR $y false if both are true
Logical True if both the operands are true else
&& $x && $y
AND false
Logical True if either of the operands is true
|| $x || $y
OR else false
Logical
! !$x True if $x is false
NOT

Example: This example describes the logical & relational operator in PHP.

<?php
$a = 80;
$b = 50;
$c = "80";

// Here var_dump function has been used to


// display structured information. We will learn
// about this function in complete details in further
// articles.
var_dump($a == $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a <> $b) + "\n";
var_dump($a === $c) + "\n";
var_dump($a !== $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>

Output:

and Success
or Success
xor Success
&& Success
|| Success
! Success

Comparison Operators: These operators are used to compare two elements and
outputs the result in boolean form. Here are the comparison operators along with their
syntax and operations in PHP.
Operator Name Syntax Operation
$x == Returns True if both the operands are
== Equal To
$y equal
$x != Returns True if both the operands are
!= Not Equal To
$y not equal
$x <> Returns True if both the operands are
<> Not Equal To
$y unequal
$x === Returns True if both the operands are
=== Identical
$y equal and are of the same type
$x == Returns True if both the operands are
!== Not Identical
$y unequal and are of different types
< Less Than $x < $y Returns True if $x is less than $y
> Greater Than $x > $y Returns True if $x is greater than $y
Less Than or $x <= Returns True if $x is less than or
<=
Equal To $y equal to $y
Greater Than or $x >= Returns True if $x is greater than or
>=
Equal To $y equal to $y

Example: This example describes the comparison operator in PHP.

<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is
negative';
?>

Output:

bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)

Conditional or Ternary Operators:

These operators are used to compare two values and take either of the results
simultaneously, depending on whether the outcome is TRUE or FALSE. These are
also used as a shorthand notation for if…else statement that we will read in the article
on decision making.

Syntax:

$var = (condition)? value1 : value2;


Here, the condition will either evaluate as true or false. If the condition evaluates to
True, then value1 will be assigned to the variable $var otherwise value2 will be
assigned to it.

Operator Name Operation


If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted
otherwise the result is on right.

Example: This example describes the Conditional or Ternary operators in PHP.

<?php
// Simple assign operator
$y = 75;
echo $y, "\n";

// Add then assign operator


$y = 100;
$y += 200;
echo $y, "\n";

// Subtract then assign operator


$y = 70;
$y -= 10;
echo $y, "\n";

// Multiply then assign operator


$y = 30;
$y *= 20;
echo $y, "\n";

// Divide then assign(quotient) operator


$y = 100;
$y /= 5;
echo $y, "\n";

// Divide then assign(remainder) operator


$y = 50;
$y %= 5;
echo $y;
?>

Output:

The number is negative

Assignment Operators: These operators are used to assign values to different


variables, with or without mid-operations. Here are the assignment operators along
with their syntax and operations, that PHP provides for the operations.
Operator Name Syntax Operation
Operand on the left obtains the value of
= Assign $x = $y
the operand on the right
$x +=
+= Add then Assign Simple Addition same as $x = $x + $y
$y
Simple subtraction same as $x = $x –
-= Subtract then Assign $x -= $y
$y
*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y
Divide then Assign
/= $x /= $y Simple division same as $x = $x / $y
(quotient)
Divide then Assign $x %=
%= Simple division same as $x = $x % $y
(remainder) $y

Example: This example describes the assignment operator in PHP.

<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");

var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>

Output:

75
300
60
600
20
0

Array Operators: These operators are used in the case of arrays. Here are the array
operators along with their syntax and operations, that PHP provides for the array
operation.

Operator Name Syntax Operation


+ Union $x + $y Union of both i.e., $x and $y
== Equality $x == $y Returns true if both has same key-value pair
!= Inequality $x != $y Returns True if both are unequal
$x === Returns True if both have the same key-value pair in
=== Identity
$y the same order and of the same type
Non- $x !==
!== Returns True if both are not identical to each other
Identity $y
<> Inequality $x <> $y Returns True if both are unequal
Example: This example describes the array operation in PHP.

<div id="highlighter_836917" class="syntaxhighlighter nogutter


"><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td
class="code"><div class="container"><div class="line number1 index0
alt2"><code class="plain"><?php</code></div><div class="line number2
index1 alt1"><code class="undefined spaces"> </code><code
class="variable">$x</code> <code class="plain">= </code><code
class="keyword">array</code><code class="plain">(</code><code
class="string">"k"</code> <code class="plain">=> </code><code
class="string">"Car"</code><code class="plain">, </code><code
class="string">"l"</code> <code class="plain">=> </code><code
class="string">"Bike"</code><code class="plain">);</code></div><div
class="line number3 index2 alt2"><code class="undefined
spaces"> </code><code class="variable">$y</code> <code
class="plain">= </code><code class="keyword">array</code><code
class="plain">(</code><code class="string">"a"</code> <code
class="plain">=> </code><code class="string">"Train"</code><code
class="plain">, </code><code class="string">"b"</code> <code
class="plain">=> </code><code class="string">"Plane"</code><code
class="plain">);</code></div><div class="line number4 index3
alt1"> </div><div class="line number5 index4 alt2"><code
class="undefined spaces"> </code><code
class="plain">var_dump(</code><code class="variable">$x</code> <code
class="plain">+ </code><code class="variable">$y</code><code
class="plain">);</code></div><div class="line number6 index5
alt1"><code class="undefined spaces"> </code><code
class="plain">var_dump(</code><code class="variable">$x</code> <code
class="plain">== </code><code class="variable">$y</code><code
class="plain">) + </code><code class="string">"\n"</code><code
class="plain">;</code></div><div class="line number7 index6
alt2"><code class="undefined spaces"> </code><code
class="plain">var_dump(</code><code class="variable">$x</code> <code
class="plain">!= </code><code class="variable">$y</code><code
class="plain">) + </code><code class="string">"\n"</code><code
class="plain">;</code></div><div class="line number8 index7
alt1"><code class="undefined spaces"> </code><code
class="plain">var_dump(</code><code class="variable">$x</code> <code
class="plain"><> </code><code class="variable">$y</code><code
class="plain">) + </code><code class="string">"\n"</code><code
class="plain">;</code></div><div class="line number9 index8
alt2"><code class="undefined spaces"> </code><code
class="plain">var_dump(</code><code class="variable">$x</code> <code
class="plain">=== </code><code class="variable">$y</code><code
class="plain">) + </code><code class="string">"\n"</code><code
class="plain">;</code></div><div class="line number10 index9
alt1"><code class="undefined spaces"> </code><code
class="plain">var_dump(</code><code class="variable">$x</code> <code
class="plain">!== </code><code class="variable">$y</code><code
class="plain">) + </code><code class="string">"\n"</code><code
class="plain">;</code></div><div class="line number11 index10
alt2"><code
class="plain">?></code></div></div></td></tr></tbody></table></div>

Output:

array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

Increment/Decrement Operators: These are called the unary operators as they work
on single operands. These are used to increment or decrement values.

Operator Name Syntax Operation


First increments $x by one, then return
++ Pre-Increment ++$x
$x
First decrements $x by one, then return
— Pre-Decrement –$x
$x
Post- First returns $x, then increment it by
++ $x++
Increment one
Post- First returns $x, then decrement it by
— $x–
Decrement one

Example: This example describes the Increment/Decrement operators in PHP.

<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>

Output:

3 First increments then prints


3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1

String Operators: This operator is used for the concatenation of 2 or more strings
using the concatenation operator (‘.’). We can also use the concatenating assignment
operator (‘.=’) to append the argument on the right side to the argument on the left
side.

Operator Name Syntax Operation


. Concatenation $x.$y Concatenated $x and $y
Concatenation and First concatenates then assigns,
.= $x.=$y
assignment same as $x = $x.$y

Example: This example describes the string operator in PHP.

<?php
$x = 50;
$y = 50;
$z = 25;

echo $x <=> $y;


echo "\n";

echo $x <=> $z;


echo "\n";

echo $z <=> $y;


echo "\n";

// We can do the same for Strings


$x = "Ram";
$y = "Krishna";

echo $x <=> $y;


echo "\n";

echo $x <=> $y;


echo "\n";

echo $y <=> $x;


?>

Output:

GeeksforGeeks!!!
GeeksforGeeks!!!
Spaceship Operators:

PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are
used to compare values but instead of returning the boolean results, it returns integer
values. If both the operands are equal, it returns 0. If the right operand is greater, it
returns -1. If the left operand is greater, it returns 1. The following table shows how it
works in detail:

Operator Syntax Operation


$x <=>
$x < $y Identical to -1 (right is greater)
$y
$x <=>
$x > $y Identical to 1 (left is greater)
$y
$x <=> Identical to -1 (right is greater) or identical to 0
$x <= $y
$y (if both are equal)
$x <=> Identical to 1 (if left is greater) or identical to
$x >= $y
$y 0 (if both are equal)
$x <=>
$x == $y Identical to 0 (both are equal)
$y
$x <=>
$x != $y Not Identical to 0
$y

Example: This example illustrates the use of the spaceship operator in PHP.

Output:

0
1
-1
1
1
-1

PHP | Bitwise Operators


Last Updated : 05 Dec, 2018



The Bitwise operators is used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then calculation is performed on the
operands. The mathematical operations such as addition , subtraction , multiplication
etc. can be performed at bit-level for faster processing. In PHP, the operators that
works at bit level are:
 & (Bitwise AND) : This is a binary operator i.e. it works on
two operand. Bitwise AND operator in PHP takes two
numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.

Syntax:

$First & $Second

This will return another number whose bits are


set if both the bit of first and second are set.

Example:

Input: $First = 5, $Second = 3

Output: The bitwise & of both these value will be 1.

Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise & will be 0001 (i.e. set
if both first and second have their bit set.)


 | (Bitwise OR) : This is also binary operator i.e. works on
two operand. Bitwise OR operator takes two numbers as
operands and does OR on every bit of two numbers. The
result of OR is 1 any of the two bits is 1.

Syntax:

$First | $Second

This will return another number whose bits are


set if either the bit of first or second are set.

Example:

Input: First = 5, Second = 3


Output: The bitwise | of both these value will be 7.

Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise | will be 0111 (i.e. set
if either first or second have their bit set.)


 ^ (Bitwise XOR ) : This is also binary operator i.e. works
on two operand. This is also known as Exclusive OR
operator. Bitwise XOR takes two numbers as operands
and does XOR on every bit of two numbers. The result of
XOR is 1 if the two bits are different.

Syntax:

$First ^ $Second

This will return another number whose bits are


set if one of the bit in first or second is
set but not both.

Example:

Input: First = 5, Second = 3

Output: The bitwise ^ of both these value will be 6.

Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise ^ will be 0110 (i.e. set
if either first or second have their bit set but
not both.)


 ~ (Bitwise NOT) : This is a unary operator i.e. works on
only one operand. Bitwise NOT operator takes one
number and inverts all bits of it.

Syntax:

~$number

This will invert all the bits of $number.


Example:

Input: number = 5

Output: The bitwise '~' of this number will be -6.

Explanation:
Binary representation of 5 is 0101. Therefore the
bitwise ~ of this will be 1010 (inverts all the
bits of the input number)


 << (Bitwise Left Shift) : This is a binary operator
i.e. works on two operand. Bitwise Left Shift
operator takes two numbers, left shifts the bits
of the first operand, the second operand decides
the number of places to shift.

Syntax:

$First << $Second

This will shift the bits of $First towards the


left. $Second decides the number of time the
bits will be shifted.

Example:

Input: First = 5, Second = 1

Output: The bitwise << of both these value will be 10.

Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise << will shift the bits of 5 one times
towards the left (i.e. 01010 )

Note: Bitwise left shift with one bit is equivalent to multiplication with 2.

 >> (Bitwise Right Shift) : This is also binary
operator i.e. works on two operand. Bitwise
Right Shift operator takes two numbers, right
shifts the bits of the first operand, the second
operand decides the number of places to shift.

Syntax:

$First >> $Second

This will shift the bits of $First towards the


right. $Second decides the number of time the
bits will be shifted.

Example:

Input: First = 5, Second = 1

Output: The bitwise >> of both these value will be 2.

Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)

Note: Bitwise right shift with one bit is equivalent to division with 2.

Below is the implementation of Bitwise Operators in PHP:

<?php
// PHP code to demonstrate Bitwise Operator.

// Bitwise AND
$First = 5;
$second = 3;
$answer = $First & $second;

print_r("Bitwise & of 5 and 3 is $answer");

print_r("\n");
// Bitwise OR
$answer = $First | $second;
print_r("Bitwise | of 5 and 3 is $answer");

print_r("\n");

// Bitwise XOR
$answer = $First ^ $second;
print_r("Bitwise ^ of 5 and 3 is $answer");

print_r("\n");

// Bitwise NOT
$answer = ~$First;
print_r("Bitwise ~ of 5 is $answer");

print_r("\n");

// Bitwise Left shift


$second = 1;
$answer = $First << $second;
print_r("5 << 1 will be $answer");

print_r("\n");

// Bitwise Right shift


$answer = $First >> $second;
print_r("5 >> 1 will be $answer");

print_r("\n");
?>

Output:

Bitwise & of 5 and 3 is 1


Bitwise | of 5 and 3 is 7
Bitwise ^ of 5 and 3 is 6
Bitwise ~ of 5 is -6
5 << 1 will be 10
5 >> 1 will be 2

PHP | Ternary Operator


Last Updated : 02 Sep, 2021




If-else and Switch cases are used to evaluate conditions and decide the flow of a
program. The ternary operator is a shortcut operator used for shortening the
conditional statements.

ternary operator: The ternary operator (?:) is a conditional operator used to perform
a simple comparison or check on a condition having simple statements. It decreases
the length of the code performing conditional operations. The order of operation of
this operator is from left to right. It is called a ternary operator because it takes three
operands- a condition, a result statement for true, and a result statement for false. The
syntax for the ternary operator is as follows.

Syntax:

(Condition) ? (Statement1) : (Statement2);

 Condition: It is the expression to be evaluated and returns a boolean value.


 Statement 1: It is the statement to be executed if the condition results in a true state.
 Statement 2: It is the statement to be executed if the condition results in a false state.

The result of this comparison can also be assigned to a variable using the assignment
operator. The syntax is as follows:

Variable = (Condition) ? (Statement1) : (Statement2);

If the statement executed depending on the condition returns any value, it will be
assigned to the variable.

Advantages of Ternary Operator: Following are some advantages of ternary


operator:

 The use of the ternary operator will make the code shorter in comparison to the IF ELSE
statement.
 The code can be quick in length in comparison to the IF ELSE statement.
 The readability of the code will increase with the usage of conditional statements.
 The use of the ternary operator makes the code simpler.

Example 1: In this example, if the value of $a is greater than 15, then 20 will be
returned and will be assigned to $b, else 5 will be returned and assigned to $b.

<?php
$a = 10;
$b = $a > 15 ? 20 : 5;
print ("Value of b is " . $b);
?>

Output:

Value of b is 5

Example 2: In this example, if the value of $age is more than or equal to 18, “Adult”
is passed to print function and printed, else “Not Adult” is passed and printed.
<?php
$age = 20;
print ($age >= 18) ? "Adult" : "Not Adult";
?>

Output:

Adult

When we use ternary operator: We use the ternary operator when we need to
simplify the if-else statements that are simply assigning values to variables depending
on a condition. An advantage of using a ternary operator is that it reduces the huge if-
else block to a single line, improving the code readability and simplify it. Very useful
while assigning variables after form submission.

Example:

Original Code:

<?php
if(isset($_POST['Name']))
$name = $_POST['Name'];
else
$name = null;

if(isset($_POST['Age']))
$age = $_POST['Age'];
else
$age = null;
?>

Reduced to the following: Thus, the ternary operator successfully reduces the if-else
block to a single line, hence serving its purpose.

<?php
$name = isset($_POST['Name'])?$_POST['Name']:null;
$age = isset($_POST['Age'])?$_POST['Age']:null;
?>

PHP | Decision Making


Last Updated : 01 Sep, 2021



PHP allows us to perform actions based on some type of conditions that may be
logical or comparative. Based on the result of these conditions i.e., either TRUE or
FALSE, an action would be performed as asked by the user. It’s just like a two- way
path. If you want something then go this way or else turn that way. To use this
feature, PHP provides us with four conditional statements:

 if statement
 if…else statement
 if…elseif…else statement
 switch statement

Let us now look at each one of these in details:

1. if
Stat
eme
nt:
This
stat
eme
nt
allo
ws
us
to
set
a
con
ditio
n.
On
bein
g
TRU
E,
the
follo
win
g
bloc
k of
cod
e
encl
ose
d
with
in
the
if
clau
se
will
be
exec
uted
.
Syntax :

2.

if (condition){
// if TRUE then execute this code
}

3.

Example:

4.
5.
6.
7.

<?php
$x = 12;

if ($x > 0) {
echo "The number is positive";
}
?>

8.

Output:

9.

The number is positive

10.
Flowchart:

11.
12. if…
else
Stat
eme
nt:
We
und
erst
ood
that
if a
con
ditio
n
will
hold
i.e.,
TRU
E,
then
the
bloc
k of
cod
e
with
in if
will
be
exec
uted
. But
wha
t if
the
con
ditio
n is
not
TRU
E
and
we
wan
t to
perf
orm
an
acti
on?
This
is
whe
re
else
com
es
into
play
. If a
con
ditio
n is
TRU
E
then
if
bloc
k
gets
exec
uted
,
othe
rwis
e
else
bloc
k
gets
exec
uted
.
Syntax:

13.

if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}

14.

Example:

15.
16.
17.
18.

<?php
$x = -12;

if ($x > 0) {
echo "The number is positive";
}

else{
echo "The number is negative";
}
?>

19.

Output:

20.

The number is negative

21.
Flowchart:

22.
23. if…elseif…
else
Statement:
This allows
us to use
multiple if…
else
statements.
We use this
when there
are multiple
conditions of
TRUE cases.
Syntax:

if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}

24.

Example:

25.
26.
27.
28.

<?php
$x = "August";

if ($x == "January") {
echo "Happy Republic Day";
}

elseif ($x == "August") {


echo "Happy Independence Day!!!";
}

else{
echo "Nothing to show";
}
?>

29.

Output:

30.

Happy Independence Day!!!

31.
Flowchart:

32.
33. switch Statement: The “switch” performs in various cases i.e., it has various cases to which it
matches the condition and appropriately executes a particular case block. It first evaluates an
expression and then compares with the values of each case. If a case matches then the same
case is executed. To use switch, we need to get familiar with two different keywords namely,
break and default.

1. The break statement is used to stop the automatic control flow into the next cases
and exit from the switch case.
2. The default statement contains the code that would execute if none of the cases
match.

Syntax:

switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;

Example:

<?php
$n = "February";

switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
echo "Its June";
break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
break;
case "September":
echo "Its September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its November";
break;
case "December":
echo "Its December";
break;
default:
echo "Doesn't exist";
}
?>

Output:

Its February
Flowchart:

Ternary Operators

In addition to all this conditional statements, PHP provides a shorthand way of writing
if…else, called Ternary Operators. The statement uses a question mark (?) and a
colon (:) and takes three operands: a condition to check, a result for TRUE and a
result for FALSE.
Syntax:

(condition) ? if TRUE execute this : otherwise execute this;

Example:

<?php
$x = -12;

if ($x > 0) {
echo "The number is positive \n";
}
else {
echo "The number is negative \n";
}

// This whole lot can be written in a


// single line using ternary operator
echo ($x > 0) ? 'The number is positive' :
'The number is negative';
?>

Output:

The number is negative


The number is negative

PHP switch Statement


Last Updated : 15 Feb, 2023



The switch statement is similar to the series of if-else statements. The switch
statement performs in various cases i.e. it has various cases to which it matches the
condition and appropriately executes a particular case block. It first evaluates an
expression and then compares it with the values of each case. If a case matches then
the same case is executed.

To use the switch, we need to get familiar with two different keywords namely, break
and default.

 break: The break statement is used to stop the automatic control flow into the next cases
and exit from the switch case.
 default: The default statement contains the code that would execute if none of the cases
match.
Flowchart of switch statement:

Syntax:

switch(expression)
{
case val1:
// Code Statement
break;
case val2:
// Code statement
break;
...

default:
// Code Statement
}

Example 1: The following code demonstrates the switch statement.

<?php

$x = 2;
switch ($x) {
case 1:
printf("Choice is 1");
break;
case 2:
printf("Choice is 2");
break;
case 3:
printf("Choice is 3");
break;
default:
printf("Choice other than 1, 2 and 3");

?>
Output
Choice is 2

Example 2:

<?php
$n='C';
switch($n)
{
case 'A':
case 'B':
printf("A and B\n");
break;

case 'C':
case 'D':
printf("C and D\n");
break;

default:printf("Alphabet is greater than D\n");

?>
Output
C and D

PHP break (Single and Nested


Loops)
Last Updated : 20 Nov, 2018



In PHP break is used to immediately terminate the loop and the program control
resumes at the next statement following the loop.
Method 1: Given an array the task is to run a loop and display all the values in array
and terminate the loop when encounter 5.

Examples:

Input : array1 = array( 1, 2, 3, 4, 5, 6, 7 )


Output : 1 2 3 4
Loop Terminated
The loop contains an if condition and when condition is true then
loop will break otherwise display the array content.

Input : array1 = array( '10', '2', '5', '20', '40' )


Output : 10 2
Loop Terminated

Program:
<?php
// PHP program to break the loop

// Declare an array and initialize it


$array = array( 1, 2, 3, 4, 5, 6, 7 );

// Use foreach loop


foreach ($array as $a) {
if ($a == 5)
break;
else
echo $a . " ";
}
echo "\n";
echo "Loop Terminated";
?>
Output:
1 2 3 4
Loop Terminated

Method 2: Given nested loops, in PHP we can use break 2 to terminate two loops as
well. Below program contains the nested loop and terminate it using break statement.
For example given two array arr1 and arr2, and the task is to display all the value of
arr2 for every value of arr1 till the value of arr1 not equal to arr2. If the value in arr1
is equal to the value of arr2 then terminate both the loops using break 2 and execute
the further statements.

Examples:

Input : arr1 = array( 'A', 'B', 'C' );


arr2 = array( 'C', 'A', 'B', 'D' );
Output : A C
Loop Terminated

Input : arr1 = array( 10, 2, 5, 20, 40 )


arr2 = array( 1, 2 )
Output :10 1 2
2 1
Loop Terminated
<?php
// PHP program to break the loop

// Declare two array and initialize it


$arr1 = array( 'A', 'B', 'C' );
$arr2 = array( 'C', 'A', 'B', 'D' );

// Use foreach loop


foreach ($arr1 as $a) {
echo "$a ";

// Ue nested loop
foreach ($arr2 as $b) {
if ($a != $b )
echo "$b ";
else
break 2;
}
echo "\n";
}

echo "\nLoop Terminated";


?>
Output:
A C
Loop Terminated

PHP continue Statement


Last Updated : 25 Aug, 2022



The continue statement is used within a loop structure to skip the loop iteration and
continue execution at the beginning of condition execution. It is mainly used to skip
the current iteration and check for the next condition.

The continue accepts an optional numeric value that tells how many loops you want
to skip. Its default value is 1.

Syntax:

loop {
// Statements
...
continue;
}

Example 1: The following code shows a simple code with a continue statement.

<?php

for ($num = 1; $num < 10; $num++)


{
if ($num % 2 == 0)
{
continue;
}
echo $num . " ";
}
?>
Output
1 3 5 7 9

Example 2: The following code shows a continue 2 statement that will continue with
the next iteration of the outer loop.

<?php

$num = 4;

while($num++ < 5)
{
echo "First Loop \n";

while(1)
{
echo "Second Loop \n";
continue 2;
}
echo "Outer value \n";
}

?>
Output
First Loop
Second Loop

PHP | Loops
Last Updated : 09 Mar, 2018



Like any other language, loop in PHP is used to execute a statement or a block of
statements, multiple times until and unless a specific condition is met. This helps the
user to save both time and effort of writing the same code multiple times.

PHP supports four types of looping techniques;

1. for loop
2. while loop
3. do-while loop
4. foreach loop

Let us now learn about each of the above mentioned loops in details:
1. for loop: This type of loops is used when the user knows in
advance, how many times the block needs to execute. That is, the
number of iterations is known beforehand. These type of loops
are also known as entry-controlled loops. There are three main
parameters to the code, namely the initialization, the test
condition and the counter.

Syntax:

2.

for (initialization expression; test condition; update


expression) {
// code to be executed
}

3.

In for loop, a loop variable is used to control the loop. First initialize this loop
variable to some value, then check whether this variable is less than or greater
than counter value. If statement is true, then loop body is executed and loop
variable gets updated . Steps are repeated till exit condition comes.

4.

o Initialization Expression: In this expression we have to initialize the loop counter to


some value. for example: $num = 1;
o Test Expression: In this expression we have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update expression
otherwise we will exit from the for loop. For example: $num <= 10;
o Update Expression: After executing loop body this expression
increments/decrements the loop variable by some value. for example: $num += 2;

Example:

<?php

// code to illustrate for loop


for ($num = 1; $num <= 10; $num += 2) {
echo "$num \n";
}

?>

Output:

1
3
5
7
9
Flow Diagram:

5. w
h
i
l
e

l
o
o
p
:

T
h
e

w
h
i
l
e

l
o
o
p

i
s

a
l
s
o

a
n

e
n
t
r
y

c
o
n
t
r
o
l

l
o
o
p

l
i
k
e

f
o
r

l
o
o
p
s

i
.
e
.
,

i
t

f
i
r
s
t

c
h
e
c
k
s

t
h
e

c
o
n
d
i
t
i
o
n

a
t

t
h
e

s
t
a
r
t

o
f

t
h
e

l
o
o
p

a
n
d

i
f
i
t
s

t
r
u
e

t
h
e
n

i
t

e
n
t
e
r
s

t
h
e

l
o
o
p

a
n
d

e
x
e
c
u
t
e
s

t
h
e

b
l
o
c
k
o
f

s
t
a
t
e
m
e
n
t
s
,

a
n
d

g
o
e
s

o
n

e
x
e
c
u
t
i
n
g

i
t

a
s

l
o
n
g

a
s

t
h
e

c
o
n
d
i
t
i
o
n

h
o
l
d
s

t
r
u
e
.

Syntax:

6.

while (if the condition is true) {


// code is executed
}

7.

Example:

8.
9.
10.
11.

<?php

// PHP code to illustrate while loops


$num = 2;

while ($num < 12) {


$num += 2;
echo $num, "\n";
}

?>

12.
Output:

13.

4
6
8
10
12

14.

Flowchart:

15.

16.
17. do-while loop: Thi
that it first enters
then checks the co
executed at least o
executing once, th
condition holds tru

Syntax:

18.

do {
//code is executed

} while (if condition is true);

19.

Example:

20.
21.
22.
23.

<?php

// PHP code to illustrate do...while loops


$num = 2;
do {
$num += 2;
echo $num, "\n";
} while ($num < 12);

?>

24.

Output:

25.

4
6
8
10
12

26.

This code would show the difference between while and do…while loop.

27.
28.
29.
30.

<?php

// PHP code to illustrate the difference of two loops


$num = 2;
// In case of while
while ($num != 2) {

echo "In case of while the code is skipped";


echo $num, "\n";

}
// In case of do...while
do {

$num++;
echo "The do...while code is executed atleast once ";

} while($num == 2);

?>

31.

Output:

32.

The code is executed at least once

33.

Flowchart:

34.
35.
36. foreach loop: This
loop is used to iterate
over arrays. For every
counter of loop, an
array element is
assigned and the next
counter is shifted to
the next element.
Syntax:

foreach (array_element as value) {


//code to be executed
}

37.

Example:

38.
39.
40.
41.

<?php

$arr = array (10, 20, 30, 40, 50, 60);


foreach ($arr as $val) {
echo "$val \n";
}

$arr = array ("Ram", "Laxman", "Sita");


foreach ($arr as $val) {
echo "$val \n";
}

?>

42.

Output:

43.

10
20
30
40
50
60
Ram
Laxman
Sita

44.

PHP while Loop


Last Updated : 22 Aug, 2022



The while loop is the simple loop that executes nested statements repeatedly while the
expression value is true. The expression is checked every time at the beginning of the
loop, and if the expression evaluates to true then the loop is executed otherwise loop
is terminated.

Flowchart of While Loop:

Syntax:

while (if the condition is true) {


// Code is executed
}

Example 1: This example uses a while loop to display numbers.

<?php

// Declare a number
$num = 10;

// While Loop
while ($num < 20) {
echo $num . "\n";
$num += 2;
}
?>
Output
10
12
14
16
18
while-endWhile loop:

Syntax:

while (if the condition is true):


// Code is executed
...
endwhile;

Example 2: This example uses while and endwhile to display the numbers.

<?php

// Declare a number
$num = 10;

// While Loop
while ($num < 20):
echo $num . "\n";
$num += 2;
endwhile;
?>
Output
10
12
14
16
18

PHP do-while Loop


Last Updated : 25 Aug, 2022



The do-while loop is very similar to the while loop, the only difference is that the do-
while loop checks the expression (condition) at the end of each iteration. In a do-
while loop, the loop is executed at least once when the given expression is “false”.
The first iteration of the loop is executed without checking the condition.

Flowchart of the do-while loop:

Syntax:
do {
// Code is executed
} while (if the condition is true);

Example 1: The following code demonstrates the do..while statement.

<?php

// Declare a number
$num = 10;

// do-while Loop
do
{
echo $num . "\n";
$num += 2;
} while ($num < 20);

?>
Output
10
12
14
16
18

Example 2:

<?php

// Declare a number
$num = 0;

// do-while Loop
do
{
$num += 5;
echo $num . "\n";

} while ($num < 20);

?>
Output
5
10
15
20

PHP for Loop


Last Updated : 25 Aug, 2022



The for loop is the most complex loop in PHP that is used when the user knows how
many times the block needs to be executed. The for loop contains the initialization
expression, test condition, and update expression (expression for increment or
decrement).

Flowchart of for Loop:

Syntax:

for (initialization expression; test condition; update expression) {


// Code to be executed
}

Loop Parameters:

 Initialization Expression: In this expression, we have to initialize the loop counter to some
value. For example: $num = 1;
 Test Condition: In this expression, we have to test the condition. If the condition evaluates to
“true” then it will execute the body of the loop and go to the update expression otherwise it
will exit from the for loop. For example: $num <= 10;
 Update Expression: After executing the loop body, this expression increments/decrements
the loop variable by some value. For example: $num += 2;

Example 1: The following code shows a simple example using for loop.

<?php

// for Loop to display numbers


for( $num = 0; $num < 20; $num += 5) {
echo $num . "\n";
}

?>
Output
0
5
10
15

Example 2: The following code shows another example of for loop.


<?php

// for Loop to display numbers


for( $num = 1; $num < 50; $num++)
{
if($num % 5 == 0)
echo $num . "\n";
}
?>
Output
5
10
15
20
25
30
35
40
45

PHP | foreach Loop


Last Updated : 25 Sep, 2019



The foreach construct provides the easiest way to iterate the array elements. It works
on array and objects both. The foreach loop though iterates over an array of elements,
the execution is simplified and finishes the loop in less time comparatively. It
allocates temporary memory for index iterations which makes the overall system to
redundant its performance in terms of memory allocation.
Syntax:

foreach( $array as $element ) {


// PHP Code to be executed
}

or

foreach( $array as $key => $element) {


// PHP Code to be executed
}

Below programs illustrate the foreach loop in PHP:

Program 1: PHP program to print the array elements using foreach loop.

<?php

// Declare an array
$arr = array("green", "blue", "pink", "white");

// Loop through the array elements


foreach ($arr as $element) {
echo "$element ";
}

?>
Output:
green blue pink white

Program 2: PHP program to print the associative array elements using foreach loop.

<?php
$employee = array(
"name" => "Robert",
"email" => "robert112233@mail.com",
"age" => 18,
"gender" => "male"

);

// Loop through employee array


foreach($employee as $key => $element) {
echo $key . ": " . $element . "<br>";
}

?>
Output:
name: Robert
email: robert112233@mail.com
age: 18
gender: male

PHP | Functions
Last Updated : 16 Dec, 2022



A function is a block of code written in a program to perform some specific task. We


can relate functions in programs to employees in a office in real life for a better
understanding of how functions work. Suppose the boss wants his employee to
calculate the annual budget. So how will this process complete? The employee will
take information about the statistics from the boss, performs calculations and calculate
the budget and shows the result to his boss. Functions works in a similar manner.
They take informations as parameter, executes a block of statements or perform
operations on this parameters and returns the result.
PHP provides us with two major types of functions:
 Built-in functions : PHP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.
 User Defined Functions : Apart from the built-in functions, PHP allows us to create our own
customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply
calling it.

Why should we use functions?

 Reusability: If we have a common code that we would like to use at various parts of a
program, we can simply contain it within a function and call it whenever required. This
reduces the time and effort of repetition of a single code. This can be done both within a
program and also by importing the PHP file, containing the function, in some other program
 Easier error detection: Since, our code is divided into functions, we can easily detect in which
function, the error could lie and fix them fast and easily.
 Easily maintained: As we have used functions in our program, so if anything or any line of
code needs to be changed, we can easily change it inside the function and the change will be
reflected everywhere, where the function is called. Hence, easy to maintain.

Creating a Function

While creating a user defined function we need to keep few things in mind:

1. Any name ending with an open and closed parenthesis is a function.


2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or underscore.
5. A function name is not case-sensitive.

Syntax:

function function_name(){
executable code;
}

Example:

<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;

return $product; //returning the product


}

// storing the returned value


$retValue = proGeek(2, 3, 5);
echo "The product is $retValue";

?>

Output:

This is Geeks for Geeks

Function Parameters or Arguments

The information or variable, within the function’s parenthesis, are called parameters.
These are used to hold the values executable during runtime. A user is free to take in
as many parameters as he wants, separated with a comma(,) operator. These
parameters are used to accept inputs during runtime. While passing the values like
during a function call, they are called arguments. An argument is a value passed to a
function and a parameter is used to hold those arguments. In common term, both
parameter and argument mean the same. We need to keep in mind that for every
parameter, we need to pass its corresponding argument.
Syntax:

function function_name($first_parameter, $second_parameter) {


executable code;
}

Example:

<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}

// Calling the function


// Passing three arguments
proGeek(2, 3, 5);
?>

Output:

The product is 30

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters. If we do not
pass any argument for a parameter with default value then PHP will use the default set
value for this parameter in the function call.
Example:

<?php

// function with default parameter


function defGeek($str, $num=12)
{
echo "$str is $num years old \n";
}

// Calling the function


defGeek("Ram", 15);

// In this call, the default value 12


// will be considered
defGeek("Adam");

?>

Output:

Ram is 15 years old


Adam is 12 years old

In the above example, the parameter $num has a default value 12, if we do not pass
any value for this parameter in a function call then this default value 12 will be
considered. Also the parameter $str has no default value , so it is compulsory.

Returning Values from Functions

Functions can also return values to the part of program from where it is called. The
return keyword is used to return value back to the part of program, from where it was
called. The returning value may be of any type including the arrays and objects. The
return statement also marks the end of the function and stops the execution after that
and returns the value.
Example:

<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;

return $product; //returning the product


}

// storing the returned value


$retValue = proGeek(2, 3, 5);
echo "The product is $retValue";

?>

Output:

The product is 30

Parameter passing to Functions

PHP allows us two ways in which an argument can be passed into a function:

 Pass by Value: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged.
That means a duplicate of the original value is passed as an argument.
 Pass by Reference: On passing arguments as pass by reference, the original value is passed.
Therefore, the original value gets altered. In pass by reference we actually pass the address
of the value, where it is stored using ampersand sign(&).

Example:

<?php

// pass by value
function valGeek($num) {
$num += 2;
return $num;
}
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
}

$n = 10;

valGeek($n);
echo "The original value is still $n \n";

refGeek($n);
echo "The original value changes to $n";

?>

Output:

The original value is still 10


The original value changes to 20

PHP Arrow Functions


Last Updated : 12 Apr, 2023



Arrow functions, also known as “short closures”, is a new feature introduced in PHP
7.4 that provides a more concise syntax for defining anonymous functions. Arrow
functions allow you to define a function in a single line of code, making your code
more readable and easier to maintain.

Syntax:

$fn = $fun(x) => some_operations

Example 1: In this example, we will declare an array and use the array_reduce()
method and arrow function to find the sum of array elements.

<?php

// Declare an array
$arr = [1, 2, 3, 4, 5, 6, 7];

$sum = array_reduce($arr, fn($carry, $item) => $carry + $item);


echo $sum;
?>

Output:

28

Example 2: In this example, we will declare an array and use the array_map()
function to display array elements in multiple of 2.

<?php

$arr = [1, 2, 3, 4, 5, 6, 7];


$res = array_map(fn($n) => $n * 2, $arr);
print_r($res);
?>

Output:

Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
[5] => 12
[6] => 14
)

Anonymous recursive function in


PHP
Last Updated : 28 Nov, 2018



Anonymous recursive function is a type of recursion in which function does not


explicitly call another function by name. This can be done either comprehensively, by
using a higher order function passing in a function as an argument and calling that
function. It can be done implicitly, via reflection features which allow one to access
certain functions depending on the current context, especially ,the current function.
In theory of computer science, anonymous recursion is significant, as anonymous
recursion is type of recursion in which one can implement recursion without requiring
named functions .
Use of Anonymous Recursion:

 Anonymous recursion is primarily of use in allowing recursion for anonymous functions.


 Particularly when they form closures or are used as callbacks, to avoid having to bind the
name of the function.

Alternatives:

 The of use named recursion and named functions.


 If an anonymous function is given,anonymous recursion can be done either by binding a
name to the function, as in named functions.

Program 1:

<?php
// PHP program to illustrate the
// Anonymous recursive function

$func = function ($limit = NULL) use (&$func) {


static $current = 10;

// if condition to check value of $current.


if ($current <= 0) {
//break the recursion
return FALSE;
}

// Print value of $current.


echo "$current\n";

$current--;

$func();
};

// Function call
$func();
?>
Output:
10
9
8
7
6
5
4
3
2
1

Program 2:
<?php
// PHP program to illustrate the
// Anonymous recursive function

$factorial = function( $num ) use ( &$factorial ) {

// Base condition of recursion


if( $num == 1 )
return 1;

// return statement when $m is not equals to 1.


return $factorial( $num - 1 ) * $num;
};

// Function call
print $factorial( 6 );
?>
Output:
720

PHP | Classes
Last Updated : 25 Mar, 2018



Like C++ and Java, PHP also supports object oriented programming

1. Classes are the blueprints of objects. One of the big differences between functions and
classes is that a class contains both data (variables) and functions that form a package called
an: ‘object’.
2. Class is a programmer-defined data type, which includes local methods and local variables.
3. Class is a collection of objects. Object has properties and behavior.

Syntax: We define our own class by starting with the keyword ‘class’ followed by the
name you want to give your new class.

<?php
class person {

}
?>

Note: We enclose a class using curly braces ( { } ) … just like you do with functions.

Given below are the programs to elaborate the use of class in Object Oriented
Programming in PHP.
The programs will illustrate the examples given in the article.
Program 1:

<?php
class GeeksforGeeks
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!
<br>';
}

// Create a new object


$obj = new GeeksforGeeks;
?>

Output:

The class "GeeksforGeeks" was initiated.

Program 2:

<?php
class GeeksforGeeks
{
// Destructor
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed!';
}

// Create a new object


$obj = new GeeksforGeeks;
?>

Output:

The class "GeeksforGeeks" was destroyed.

Reference:

PHP | Constructors and Destructors


Last Updated : 02 Dec, 2022




Constructors are special member functions for initial settings of newly created object
instances from a class, which is the key part of the object-oriented concept in PHP5.
Constructors are the very basic building blocks that define the future object and its
nature. You can say that the Constructors are the blueprints for object creation
providing values for member functions and member variables.
Once the object is initialized, the constructor is automatically called. Destructors are
for destroying objects and automatically called at the end of execution.
In this article, we are going to learn about object-oriented concepts of constructors
and destructors.
Both are special member functions of any class with different concepts but the same
name except destructors are preceded by a ~ Tilda operator.
Syntax:

 __construct():

function __construct()
{
// initialize the object and its properties by assigning
//values
}

 __destruct():

function __destruct()
{
// destroying the object or clean up resources here
}

Note: The constructor is defined in the public section of the Class. Even the values to
properties of the class are set by Constructors.
Constructor types:

 Default Constructor:It has no parameters, but the values to the default constructor can be
passed dynamically.
 Parameterized Constructor: It takes the parameters, and also you can pass different values
to the data members.
 Copy Constructor: It accepts the address of the other objects as a parameter.

Inheritance: As Inheritance is an object-oriented concept, the Constructors are


inherited from parent class to child class derived from it. Whenever the child class has
constructor and destructor of their own, these are called in order of priority or
preference.
Pre-defined Default Constructor: By using function __construct(), you can define a
constructor.
Note: In the case of Pre-defined Constructor(__construct) and user-defined
constructor in the same class, the Pre-defined Constructor becomes Constructor while
user-defined constructor becomes the normal method.
Program:

<?PHP
class Tree
{
function Tree()
{
echo "Its a User-defined Constructor of the class
Tree";
}

function __construct()
{
echo "Its a Pre-defined Constructor of the class
Tree";
}
}

$obj= new Tree();


?>

Output:

Its a Pre-defined Constructor of the class Tree

Parameterized Constructor: The constructor of the class accepts arguments or


parameters.
The -> operator is used to set value for the variables. In the constructor method, you
can assign values to the variables during object creation.
Program:

<?php

class Employee
{

Public $name;

Public $position;

function __construct($name,$position)

{
// This is initializing the class properties
$this->name=$name;
$this->position=$position;
}
function show_details()
{
echo $this->name." : ";
echo "Your position is ".$this->profile."\n";
}
}

$employee_obj= new Employee("Rakesh","developer");


$employee_obj->show_details();

$employee2= new Employee("Vikas","Manager");


$employee2->show_details();

?>

Output:

Rakesh : Your position is developer


Vikas : Your position is Manager

Constructors start with two underscores and generally look like normal PHP
functions. Sometimes these constructors are called as magic functions starting with
two underscores and with some extra functionality than normal methods. After
creating an object of some class that includes constructor, the content of constructor
will be automatically executed.
Note: If the PHP Class has a constructor, then at the time of object creation, the
constructor of the class is called. The constructors have no Return Type, so they do
not return anything not even void.
Advantages of using Constructors:

 Constructors provides the ability to pass parameters which are helpful in automatic
initialization of the member variables during creation time .
 The Constructors can have as many parameters as required and they can be defined with the
default arguments.
 They encourage re-usability avoiding re-initializing whenever instance of the class is created .
 You can start session in constructor method so that you don’t have to start in all the
functions everytime.
 They can call class member methods and functions.
 They can call other Constructors even from Parent class.

Note : The __construct() method always have the public visibility factor.
Program:

<?php
class ParentClass
{
function __construct()
{
print "Parent class constructor.\n";
}
}

class ChildClass extends Parentclass


{
function __construct()
{
parent::__construct();
print "Child Class constructor";
}
}
$obj = new ParentClass();
$obj = new ChildClass();

?>

Output

Parent class constructor.


Parent class constructor.
Child Class constructor

Note: Whenever child class object is created, the constructor of subclass will be
automatically called.
Destructor: Destructor is also a special member function which is exactly the reverse
of constructor method and is called when an instance of the class is deleted from the
memory. Destructors (__destruct ( void): void) are methods which are called when
there is no reference to any object of the class or goes out of scope or about to release
explicitly.
They don’t have any types or return value. It is just called before de-allocating
memory for an object or during the finish of execution of PHP scripts or as soon as
the execution control leaves the block.
Global objects are destroyed when the full script or code terminates. Cleaning up of
resources before memory release or closing of files takes place in the destructor
method, whenever they are no longer needed in the code. The automatic destruction
of class objects is handled by PHP Garbage Collector.

~ ClassName()
{

Note: The destructor method is called when the PHP code is executed completely by
its last line by using PHP exit() or die() functions.
Program:

<?php
class SomeClass
{

function __construct()
{
echo "In constructor, ";
$this->name = "Class object! ";
}

function __destruct()
{
echo "destroying " . $this->name . "\n";
}
}
$obj = new Someclass();

?>

Output:

In constructor, destroying Class object!

Note: In the case of inheritance, and if both the child and parent Class have
destructors then, the destructor of the derived class is called first, and then the
destructor of the parent class.

Advantages of destructors:

 Destructors give chance to objects to free up memory allocation , so that enough space is
available for new objects or free up resources for other tasks.
 It effectively makes programs run more efficiently and are very useful as they carry out clean
up tasks.

Comparison between __constructors and __destructors:

Constructors Destructors
Accepts one or more arguments. No arguments are passed. Its void.
function name is _construct(). function name is _destruct()
It has same name as the class with
It has same name as the class.
prefix ~tilda.
Constructor is involved Destructor is involved
automatically when the object is automatically when the object is
Constructors Destructors
created. destroyed.
Used to de-initialize objects
Used to initialize the instance of
already existing to free up memory
a class.
for new accommodation.
Used to initialize data members of Used to make the object perform
class. some task before it is destroyed.
Constructors can be overloaded. Destructors cannot be overloaded.
It is called each time a class is It is called automatically at the
instantiated or object is created. time of object deletion .
Allocates memory. It deallocates memory.
Multiple constructors can exist in Only one Destructor can exist in a
a class. class.
If there is a derived class
inheriting from base class and the The destructor of the derived class
object of the derived class is is called and then the destructor
created, of base class just the reverse
the constructor of base class is order of
created and then the constructor constructor.
of the derived class.
The concept of copy constructor is
allowed where an object is
initialized from the address of No such concept is allowed.
another object .

PHP | Access Specifiers


Last Updated : 17 Sep, 2021



In the PHP each and every property of a class in must have one of three visibility
levels, known as public, private, and protected.

 Public: Public properties can be accessed by any code, whether that code is inside or outside
the class. If a property is declared public, its value can be read or changed from anywhere in
your script.
 Private: Private properties of a class can be accessed only by code inside the class. So if we
create a property that’s declared private, only methods and objects inside the same class can
access its contents.
 Protected: Protected class properties are a bit like private properties in that they can’t be
accessed by code outside the class, but there’s one little difference in any class that inherits
from the class i.e. base class can also access the properties.

Generally speaking, it’s a good idea to avoid creating public properties wherever
possible. Instead, it’s safer to create private properties, then to create methods that
allow code outside the class to access those properties. This means that we can control
exactly how our class’s properties are accessed.
Note: If we attempt to access the property outside the class, PHP generates a fatal
error.
PHP Access Specifier’s feasibility with Class, Sub Class and Outside World :

Class Member Access Access from Accessible from Accessible by


Specifier own class derived class Object
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes

Below examples illustrate the Access Specifier of PHP:

 Example 1: In this example, we will see the Public Access Specifier.

<?php
class GeeksForGeeks
{
public $x = 100 ; # public attributes
public $y = 50 ;
function add()
{
echo $a = $this->x + $this->y ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function sub()
{
echo $s = $this->x - $this->y ;
}

$obj = new child;

// It will return the addition result


$obj->add() ;

// It's a derived class of the main class,


// which has a public object and therefore can be
// accessed, returning the subtracted result.
$obj->sub() ;

?>
 Output:

150 50

 Example 2: In this example, we will see the Private Access Specifier

<?php
class GeeksForGeeks
{
private $a = 75 ; # private attributes
private $b = 5 ;
private function div() # private member function
{
echo $d = $this->a / $this->b ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function mul()
{
echo $m = $this->a * $this->b ;
}

$obj= new child;

// It's supposed to return the division result


// but since the data and function are private
// they can't be accessed by a derived class
// which will lead to fatal error .
$obj->div();

// It's a derived class of the main class,


// which's accessing the private data
// which again will lead to fatal error .
$obj->mul();
?>

 Output:

PHP Fatal error: Uncaught Error: Call to private method


GeeksForGeeks::div() from context '' in /home/cg/root/8030907/
main.php:22 Stack trace:#0 {main} thrown in /home/cg/root/8030907/
main.php on line 22

 Example 3: In this example, we will see the Protected Access Specifier.


<?php
class GeeksForGeeks
{
protected $x = 1000 ; # protected attributes
protected $y = 100 ;
function div()
{
echo $d = $this->x / $this->y ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function sub()
{
echo $s = $this->x - $this->y ;
}

}
class derived # Outside Class
{
function mul()
{
echo $m = $this->x * $this->y ;
}

}
$obj= new child;

// It will return the division result


$obj->div();

// Since it's a derived class of the main class,


$obj->sub();

// Since it's an outside class, therefore it


// will produce a fatal error .
$obj->mul();

?>

 Output :

10
900
Fatal error: Uncaught Error: Call to undefined method
child::mul() in /home/cg/root/8030907/main.php:32
Multiple Inheritance in PHP
Last Updated : 01 Aug, 2021



Multiple Inheritance is the property of the Object Oriented Programming languages in


which child class or sub class can inherit the properties of the multiple parent classes
or super classes.

PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using
Traits in PHP instead of classes, we can implement it.

Traits (Using Class along with Traits): The trait is a type of class which enables
multiple inheritance. Classes, case classes, objects, and traits can all extend no more
than one class but can extend multiple traits at the same time.
Syntax:

class child_class_name extends parent_class_name {


use trait_name;
...
...
child_class functions
}

Example:

<?php

// Class Geeks
class Geeks {
public function sayhello() {
echo "Hello";
}
}

// Trait forGeeks
trait forGeeks {
public function sayfor() {
echo " Geeks";
}
}

class Sample extends Geeks {


use forGeeks;
public function geeksforgeeks() {
echo "\nGeeksforGeeks";
}
}

$test = new Sample();


$test->sayhello();
$test->sayfor();
$test->geeksforgeeks();
?>
Output:
Hello Geeks
GeeksforGeeks

In the above program “traits” has been used along with parent class. There is “class”
named “Geeks” which contains function sayhello() and a “trait” named “forGeeks”
which contains function geeksforgeeks() and there is child class named “Sample” and
we are creating the object of this class named “test” and using it we are invoking all
the functions of a class and a trait.

Traits (Using Multiple Traits): Multiple Traits can be inserted into a class by listing
them in the use statement, separated by commas.
Syntax:

class child_class_name {
use trait_name;
...
...
child_class functions
}

Example:

<?php

// trait Geeks
trait Geeks {
public function sayhello() {
echo "Hello";
}
}

// trait forGeeks
trait forGeeks {
public function sayfor() {
echo " Geeks";
}
}

class Sample {
use Geeks;
use forGeeks;
public function geeksforgeeks() {
echo "\nGeeksforGeeks";
}
}

$test = new Sample();


$test->sayhello();
$test->sayfor();
$test->geeksforgeeks();
?>
Output:
Hello Geeks
GeeksforGeeks

In the above program “traits” has been used. There are two traits named “Geeks”
which contains function sayhello() and “forGeeks” which contains function
geeksforgeeks() respectively and there is a child class “Sample” and we are creating
the object of this class named “test” and using it we are invoking all the functions of
traits.

Interface (Using Class along with Interface):


Syntax:

class child_class_name extends parent_class_name implements


interface_name1, ...

Example:

<?php

class A {
public function insideA() {
echo "I am in class A";
}
}

interface B {
public function insideB();
}

class Multiple extends A implements B {


function insideB() {
echo "\nI am in interface";
}

public function insidemultiple() {


echo "\nI am in inherited class";
}
}

$geeks = new multiple();


$geeks->insideA();
$geeks->insideB();
$geeks->insidemultiple();
?>
Output:
I am in class A
I am in interface
I am in inherited class

In the above program Interface “B” has been used along with the class “A” to
implement multiple inheritance. The important point to remember is, it can’t define
the function inside interface, it should be defined inside the child class “Multiple”.
We are invoking all the functions using the child class (Multiple) object named
“geeks”.

Interface (Using Multiple Interface):

Syntax:

class child_class_name implements interface_name1,


interface_name2, ...

Example:

<?php

interface C {
public function insideC();
}

interface B {
public function insideB();
}

class Multiple implements B, C {

// Function of the interface B


function insideB() {
echo "\nI am in interface B";
}
// Function of the interface C
function insideC() {
echo "\nI am in interface C";
}

public function insidemultiple()


{
echo "\nI am in inherited class";
}
}

$geeks = new multiple();


$geeks->insideC();
$geeks->insideB();
$geeks->insidemultiple();
?>
Output:
I am in interface C
I am in interface B
I am in inherited class

PHP | Access Specifiers


Last Updated : 17 Sep, 2021



In the PHP each and every property of a class in must have one of three visibility
levels, known as public, private, and protected.

 Public: Public properties can be accessed by any code, whether that code is inside or outside
the class. If a property is declared public, its value can be read or changed from anywhere in
your script.
 Private: Private properties of a class can be accessed only by code inside the class. So if we
create a property that’s declared private, only methods and objects inside the same class can
access its contents.
 Protected: Protected class properties are a bit like private properties in that they can’t be
accessed by code outside the class, but there’s one little difference in any class that inherits
from the class i.e. base class can also access the properties.

Generally speaking, it’s a good idea to avoid creating public properties wherever
possible. Instead, it’s safer to create private properties, then to create methods that
allow code outside the class to access those properties. This means that we can control
exactly how our class’s properties are accessed.
Note: If we attempt to access the property outside the class, PHP generates a fatal
error.
PHP Access Specifier’s feasibility with Class, Sub Class and Outside World :
Class Member Access Access from Accessible from Accessible by
Specifier own class derived class Object
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes

Below examples illustrate the Access Specifier of PHP:

 Example 1: In this example, we will see the Public Access Specifier.

<?php
class GeeksForGeeks
{
public $x = 100 ; # public attributes
public $y = 50 ;
function add()
{
echo $a = $this->x + $this->y ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function sub()
{
echo $s = $this->x - $this->y ;
}

$obj = new child;

// It will return the addition result


$obj->add() ;

// It's a derived class of the main class,


// which has a public object and therefore can be
// accessed, returning the subtracted result.
$obj->sub() ;

?>

 Output:

150 50

 Example 2: In this example, we will see the Private Access Specifier


<?php
class GeeksForGeeks
{
private $a = 75 ; # private attributes
private $b = 5 ;
private function div() # private member function
{
echo $d = $this->a / $this->b ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function mul()
{
echo $m = $this->a * $this->b ;
}

$obj= new child;

// It's supposed to return the division result


// but since the data and function are private
// they can't be accessed by a derived class
// which will lead to fatal error .
$obj->div();

// It's a derived class of the main class,


// which's accessing the private data
// which again will lead to fatal error .
$obj->mul();
?>

 Output:

PHP Fatal error: Uncaught Error: Call to private method


GeeksForGeeks::div() from context '' in /home/cg/root/8030907/
main.php:22 Stack trace:#0 {main} thrown in /home/cg/root/8030907/
main.php on line 22

 Example 3: In this example, we will see the Protected Access Specifier.

<?php
class GeeksForGeeks
{
protected $x = 1000 ; # protected attributes
protected $y = 100 ;
function div()
{
echo $d = $this->x / $this->y ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function sub()
{
echo $s = $this->x - $this->y ;
}

}
class derived # Outside Class
{
function mul()
{
echo $m = $this->x * $this->y ;
}

}
$obj= new child;

// It will return the division result


$obj->div();

// Since it's a derived class of the main class,


$obj->sub();

// Since it's an outside class, therefore it


// will produce a fatal error .
$obj->mul();

?>

 Output :

10
900
Fatal error: Uncaught Error: Call to undefined method
child::mul() in /home/cg/root/8030907/main.php:32

PHP | Constants
Last Updated : 09 Mar, 2018



Constants are either identifiers or simple names that can be assigned any fixed values.
They are similar to a variable except that they can never be changed. They remain
constant throughout the program and cannot be altered during execution. Once a
constant is defined, it cannot be undefined or redefined. Constant identifiers should be
written in upper case following the convention. By default, a constant is always case-
sensitive, unless mentioned. A constant name must never start with a number. It
always starts with a letter or underscores, followed by letter, numbers or underscore.
It should not contain any special characters except underscore, as mentioned.

Creating a PHP Constant

The define() function in PHP is used to create a constant as shown below:


Syntax:

define(name, value, case_insensitive)

The parameters are as follows:

 name: The name of the constant.


 value: The value to be stored in the constant.
 case_insensitive: Defines whether a constant is case insensitive. By default this value is False,
i.e., case sensitive.

Example:

<?php

// This creates a case-sensitive constant


define("WELCOME", "GeeksforGeeks");
echo WELCOME, "\n";

// This creates a case-insensitive constant


define("HELLO", "GeeksforGeeks", true);
echo hello;

?>

Output:

GeeksforGeeks
GeeksforGeeks

constant() function

Instead of using the echo statement ,there is an another way to print constants using
the constant() function.

Syntax
constant(name)

Example:

<?php

define("WELCOME", "GeeksforGeeks!!!");

echo WELCOME, "\n";

echo constant("WELCOME");
// same as previous

?>

Output:

GeeksforGeeks!!!
GeeksforGeeks!!!

Constants are Global: By default, constants are automatically global, and can be
used throughout the script, accessible inside and outside of any function.
Example:

<?php

define("WELCOME", "GeeksforGeeks");

function testGlobal() {
echo WELCOME;
}

testGlobal();

?>
GeeksforGeeks

Constants vs Variables

 A constant, once defined can never be undefined but a variable can be easily undefined.
 There is no need to use dollar sign($) before constants during assignment but while declaring
variables we use a dollar sign.
 A constant can only be defined using a define() function and not by any simple assignment.
 Constants dont need to follow any variable scoping rules and can be defined anywhere.

Abstract Classes in PHP


Last Updated : 19 Jul, 2019



Abstract classes are the classes in which at least one method is abstract. Unlike C++
abstract classes in PHP are declared with the help of abstract keyword. Use of abstract
classes are that all base classes implementing this class should give implementation of
abstract methods declared in parent class. An abstract class can contain abstract as
well as non abstract methods.

<?php

// Abstract class example in PHP


abstract class base
{
// This is abstract function
abstract function printdata();

// This is not abstract function


function pr()
{
echo "Base class";
}
}
?>

Following are some important facts about abstract classes in PHP.

 Like Java, PHP also an instance


of abstract class can not be
created.

Example:




<?php

// Abstract class
abstract class Base {
// This is abstract function
abstract function printdata();
}
class Derived extends base {
function printdata() {
echo "Derived class";
}
}

// Uncommenting the following line will


// cause compiler error as the line tries
// to create an instance of abstract class.
// $b = new Base();

$b1 = new Derived;


$b1->printdata();
?>

Output:

Derived class


 Like C++ or Java abstract class
in PHP can contain constructor
also.

Example:




<?php

// Abstract class
abstract class Base {
function __construct() {
echo "this is abstract class constructor ";
}

// This is abstract function


abstract function printdata();
}
class Derived extends base {
function __construct() {
echo "\n Derived class constructor";
}
function printdata() {
echo "\n Derived class printdata function";
}
}
$b1 = new Derived;
$b1->printdata();
?>


Output:

Derived class constructor


Derived class printdata function


 Unlike Java, an abstract class
can not be created which does
not contains at least one
abstract method in PHP. If we
run the following example
then it will display an error
message.

Example:




<?php

// example to understand that an abstract


// class can not contain an method with
// body in php
abstract class Base {
abstract function printdata() {
echo "Parent class printdata";
}
}
?>

Runtime Errors:

PHP Fatal error: Abstract function Base::printdata() cannot


contain body
in /home/a7540402ade5337d505a779cf4797b38.php on line 7

PHP | Interface
Last Updated : 03 Nov, 2018


An Interface allows the users to create programs, specifying the public methods that a
class must implement, without involving the complexities and details of how the
particular methods are implemented. It is generally referred to as the next level of
abstraction. It resembles the abstract methods, resembling the abstract classes. An
Interface is defined just like a class is defined but with the class keyword replaced by
the interface keyword and just the function prototypes. The interface contains no data
variables. The interface is helpful in a way that it ensures to maintain a sort of
metadata for all the methods a programmer wishes to work on.

Creating an Interface

Following is an example of how to define an interface using the interface keyword.

<?php

interface MyInterfaceName {
public function methodA();
public function methodB();
}

?>

Few characteristics of an Interface are:

 An interface consists of methods that have no implementations, which means the interface
methods are abstract methods.
 All the methods in interfaces must have public visibility scope.
 Interfaces are different from classes as the class can inherit from one class only whereas the
class can implement one or more interfaces.

To implement an interface, use the implements operator as follows:

<?php

class MyClassName implements MyInterfaceName{


public function methodA() {

// method A implementation
}
public function methodB(){

// method B implementation
}
}

?>
Concrete Class: The class which implements an interface is called the Concrete
Class. It must implement all the methods defined in an interface. Interfaces of the
same name can’t be implemented because of ambiguity error. Just like any class, an
interface can be extended using the extends operator as follows:

<?php

interface MyInterfaceName1{

public function methodA();

interface MyInterfaceName2 extends MyInterfaceName1{

public function methodB();


}

?>

Example:

<?php

interface MyInterfaceName{

public function method1();


public function method2();

class MyClassName implements MyInterfaceName{

public function method1(){


echo "Method1 Called" . "\n";
}

public function method2(){


echo "Method2 Called". "\n";
}
}

$obj = new MyClassName;


$obj->method1();
$obj->method2();

?>
Output:
Method1 Called
Method2 Called

Advantages of PHP Interface


 An interface allows unrelated classes to implement the same set of methods, regardless of
their positions in the class inheritance hierarchy.
 An interface can model multiple inheritances because a class can implement more than one
interface whereas it can extend only one class.
 The implementation of an inheritance will save the caller from full implementation of object
methods and focus on just he objects interface, therefore, the caller interface remains
unaffected.

Static Function in PHP


Last Updated : 31 Jul, 2021



In certain cases, it is very handy to access methods and properties in terms of a class
rather than an object. This can be done with the help of static keyword. Any method
declared as static is accessible without the creation of an object. Static functions are
associated with the class, not an instance of the class. They are permitted to access
only static methods and static variables. To add a static method to the class, static
keyword is used.

public static function test()


{
// Method implementation
}

They can be invoked directly outside the class by using scope resolution operator (::)
as follows:

MyClass::test();

Example: This example illustrates static function as counter.

<?php
/* Use static function as a counter */

class solution {

static $count;

public static function getCount() {


return self::$count++;
}
}

solution::$count = 1;

for($i = 0; $i < 5; ++$i) {


echo 'The next value is: '.
solution::getCount() . "\n";
}

?>
Output:
The next value is: 1
The next value is: 2
The next value is: 3
The next value is: 4
The next value is: 5

When to define static methods ?


The static keyword is used in the context of variables and methods that are common
to all the objects of the class. Therefore, any logic which can be shared among
multiple instances of a class should be extracted and put inside the static method. PHP
static methods are most typically used in classes containing static methods only often
called utility classes of PHP frameworks like Laravel and CakePHP.

Below is the PHP code which shows the use of static methods.

Example: This example illustrates the static method in PHP.

<?php
/* Use of static method in PHP */

class A {

public function test($var = "Hello World") {


$this->var = $var;
return $this->var;
}
}

class B {
public static function test($var) {
$var = "This is static";
return $var;
}
}

// Creating Object of class A


$obj = new A();

echo $obj->test('This is non-static');


echo "\n";
echo B::test('This is non-static');

?>
Output:
This is non-static
This is static
However, a static method doesn’t let you define explicit dependencies and includes
global variables in the code that can be accessed from anywhere. This can affect the
scalability of an application. Moreover, you will have a tough time performing
automated testing on classes containing static methods. Therefore, they should be
used for utilities and not for convenience reasons.

PHP is a server-side scripting language designed specifically for web development.


You can learn PHP from the ground up by following this PHP Tutorial and PHP
Examples.

PHP | Namespace
Last Updated : 04 Oct, 2021



Like C++, PHP Namespaces are the way of encapsulating items so that same names
can be reused without name conflicts.

 It can be seen as an abstract concept in many places. It allows redeclaring the same
functions/classes/interfaces/constant functions in the separate namespace without getting
the fatal error.
 A namespace is a hierarchically labeled code block holding a regular PHP code.
 A namespace can contain valid PHP code.
 Namespace affects following types of code: classes (including abstracts and traits), interfaces,
functions, and constants.
 Namespaces are declared using the namespace keyword.

A namespace must be declared the namespace at the top of the file before any other
code – with one exception: the declare keyword.

<?php
namespace MyNamespaceName {

// Regular PHP code


function hello()
{
echo 'Hello I am Running from a namespace!';
}
}
?>

If namespace is declared globally, then declare it without any name.

<?php
namespace {
// Global space!
}
?>

Multiple namespaces can be declared within a single PHP code.

<?php
namespace MyNamespace1 {

namespace MyNamespace2 {

namespace {

}
?>

A namespace is used to avoid conflicting definitions and introduce more flexibility


and organization in the code base. Just like directories, namespace can contain a
hierarchy know as subnamespaces. PHP uses the backslash as its namespace
separator.
Example:

<?php
namespace MyNamespaceName;
function hello()
{
echo 'Hello I am Running from a namespace!';
}

// Resolves to MyNamespaceName\hello
hello();

// Explicitly resolves to MyNamespaceName\hello


namespace\hello();
?>

Aliasing in Namespaces

Importing is achieved by using the ‘use’ keyword. Optionally, It can specify a custom
alias with the ‘as’ keyword.
Example:

<?php
namespace MyNamespaceName;

require 'project/database/connection.php';

use Project\Database\Connection as Connection;

$connection = new Connection();

use Project\Database as Database;

$connection = new Database\Connection();


?>

It is possible to dynamically call namespaced code, dynamic importing is not


supported.

<?php
namespace OtherProject;

$title = 'geeks';

// This is valid PHP


require 'project/blog/title/' . $title . '.php';

// This is not
use Project\Blog\title\$title;
?>

You might also like