Module 2 PHP
Module 2 PHP
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP indexed array can store numbers, strings or any object. PHP indexed array is also
known as numeric array.
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
Syntax
2. <?php
3. $season=array("summer","winter","spring","autumn");
4. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
5. ?>
Output:
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
3) PHP array_chunk() function
PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can
divide array into many parts.
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
4
5) PHP sort() function
PHP sort() function sorts all the elements in an array.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
Syntax
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
sonoo
smith
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of curly
braces ({}). All its properties and methods go inside the braces:
Syntax
<?php
class Fruit {
// code goes here...
}
?>
Below we declare a class named Fruit consisting of two properties ($name and $color) and two
methods set_name() and get_name() for setting and getting the $name property:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Define Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has all
the properties and methods defined in the class, but they will have different property values.
In the example below, $apple and $banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
In the example below, we add two more methods to class Fruit, for setting and getting the $color
property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
So, where can we change the value of the $name property? There are two ways:
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
If you create a __construct() function, PHP will automatically call this function when you create an
object from a class.
Notice that the construct function starts with two underscores (__)!
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
If you create a __destruct() function, PHP will automatically call this function at the end of the script.
Notice that the destruct function starts with two underscores (__)!
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
<?php
class Fruit {
public $name;
public $color;
public - the property or method can be accessed from everywhere. This is default
protected - the property or method can be accessed within the class and by classes derived
from that class
private - the property or method can ONLY be accessed within the class
In the following example we have added three different access modifiers to three properties (name,
color, and weight). Here, if you try to set the name property it will work fine (because the name
property is public, and can be accessed from everywhere). However, if you try to set the color or
weight property it will result in a fatal error (because the color and weight property are protected and
private):
In the next example we have added access modifiers to two functions. Here, if you try to call the
set_color() or the set_weight() function it will result in a fatal error (because the two functions are
considered protected and private), even if all the properties are public:
Example
<?php
class Fruit {
public $name;
public $color;
public $weight;
The child class will inherit all the public and protected properties and methods from the parent class.
In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
Example Explained
The Strawberry class is inherited from the Fruit class.
This means that the Strawberry class can use the public $name and $color properties as well as the
public __construct() and intro() methods from the Fruit class because of inheritance.
In the example above we see that if we try to call a protected method (intro()) from outside the class,
we will receive an error. public methods will work fine!
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
Look at the example below. The __construct() and intro() methods in the child class (Strawberry)
will override the __construct() and intro() methods in the parent class (Fruit):
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
Example
<?php
final class Fruit {
// some code
}
<?php
class Fruit {
final public function intro() {
// some code
}
}
Class constants are case-sensitive. However, it is recommended to name the constants in all
uppercase letters.
We can access a constant from outside the class by using the class name followed by the scope
resolution operator (::) followed by the constant name, like here:
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo Goodbye::LEAVING_MESSAGE;
?>
Or, we can access a constant from inside the class by using the self keyword followed by the scope
resolution operator (::) followed by the constant name, like here:
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}
An abstract class is a class that contains at least one abstract method. An abstract method is a method
that is declared, but not implemented in the code.
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>
When inheriting from an abstract class, the child class method must be defined with the same name,
and the same or a less restricted access modifier. So, if the abstract method is defined as protected,
the child class method must be defined as either protected or public, but not private. Also, the type
and number of required arguments must be the same. However, the child classes may have optional
arguments in addition.
So, when a child class is inherited from an abstract class, we have the following rules:
The child class method must be defined with the same name and it redeclares the parent
abstract method
The child class method must be defined with the same or a less restricted access modifier
The number of required arguments must be the same. However, the child class may have
optional arguments in addition
Interfaces make it easy to use a variety of different classes in the same way. When one or more
classes use the same interface, it is referred to as "polymorphism".
<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
public function someMethod3() : string;
}
?>
A class that implements an interface must implement all of the interface's methods.
<?php
interface Animal {
public function makeSound();
}
Using interfaces, we can write some code which can work for all of the animals even if each animal
behaves differently:
Example
<?php
// Interface definition
interface Animal {
public function makeSound();
}
// Class definitions
class Cat implements Animal {
public function makeSound() {
echo " Meow ";
}
}
So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and
abstract methods that can be used in multiple classes, and the methods can have any access modifier
(public, private, or protected).
Traits are declared with the trait keyword:
<?php
trait TraitName {
// some code...
}
?>
Syntax
<?php
class MyClass {
use TraitName;
}
?>
Example
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1;
}
Example Explained
Here, we declare one trait: message1. Then, we create a class: Welcome. The class uses the trait, and
all the methods in the trait will be available in the class.
If other classes need to use the msg1() function, simply use the message1 trait in those classes. This
reduces code duplication, because there is no need to redeclare the same method over and over again.
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
To access a static method use the class name, double colon (::), and the method name:
Syntax
ClassName::staticMethod();
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
Example Explained
Here, we declare a static method: welcome(). Then, we call the static method by using the class
name, double colon (::), and the method name (without creating an instance of the class first).
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
new greeting();
?>
Static methods can also be called from methods in other classes. To do this, the static method should
be public:
To call a static method from a child class, use the parent keyword inside the child class. Here, the
static method can be public or protected.
<?php
class ClassName {
public static $staticProp = "W3Schools";
}
?>
To access a static property use the class name, double colon (::), and the property name:
Syntax
ClassName::$staticProp;
Example Explained
Here, we declare a static property: $value. Then, we echo the value of the static property by using the
class name, double colon (::), and the property name (without creating a class first).
Example
<?php
class pi {
public static $value=3.14159;
public function staticValue() {
return self::$value;
}
}
PHP Namespaces
Namespaces are qualifiers that solve two different problems:
1. They allow for better organization by grouping classes that work together to perform a task
2. They allow the same name to be used for more than one class
For example, you may have a set of classes which describe an HTML table, such as Table, Row and
Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed.
Namespaces can be used to organize the classes into two different groups while also preventing the
two classes Table and Table from being mixed up.
Declaring a Namespace
Namespaces are declared at the beginning of a file using the namespace keyword:
<?php
namespace Html;
?>
A namespace declaration must be the first thing in the PHP file. The following code would be
invalid:
<?php
echo "Hello World!";
namespace Html;
...
?>
Constants, classes and functions declared in this file will belong to the Html namespace:
Example
Create a Table class in the Html namespace:
<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>
<!DOCTYPE html>
<html>
<body>
<?php
$table->message();
?>
</body>
</html>
Syntax
Declare a namespace called Html inside a namespace called Code:
<?php
namespace Code\Html;
?>
Using Namespaces
Any code that follows a namespace declaration is operating inside the namespace, so classes that
belong to the namespace can be instantiated without any qualifiers. To access classes from outside a
namespace, the class needs to have the namespace attached to it.
Example
Use classes from the Html namespace:
<?php
$table = new Html\Table();
$row = new Html\Row();
?>
When many classes from the same namespace are being used at the same time, it is easier to use
the namespace keyword:
Example
Use classes from the Html namespace without the need for the Html\qualifier:
<?php
namespace Html;
$table = new Table();
$row = new Row();
?>
The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function
arguments and function return values.
<?php
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
All arrays are iterables, so any array can be used as an argument of a function that requires an
iterable.
Iterators
Any object that implements the Iterator interface can be used as an argument of a function that
requires an iterable.
An iterator contains a list of items and provides methods to loop through them. It keeps a pointer to
one of the elements in the list. Each item in the list should have a key which can be used to find the
item.
current() - Returns the element that the pointer is currently pointing to. It can be any data
type
key() Returns the key associated with the current element in the list. It can only be an integer,
float, boolean or string
next() Moves the pointer to the next element in the list
rewind() Moves the pointer to the first element in the list
valid() If the internal pointer is not pointing to any element (for example, if next() was called
at the end of the list), this should return false. It returns true in any other case