0% found this document useful (0 votes)
2 views

Module 2 Php

Module 2 of the PHP course covers arrays, their types (indexed, associative, and multidimensional), and how to declare them using both the array() function and square brackets. It also introduces PHP array functions for manipulation, string functions, date and time formatting, file handling, and object-oriented programming concepts including classes, objects, constructors, and destructors. The module emphasizes the advantages of OOP and provides examples for practical understanding.

Uploaded by

Leslie Qwer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 2 Php

Module 2 of the PHP course covers arrays, their types (indexed, associative, and multidimensional), and how to declare them using both the array() function and square brackets. It also introduces PHP array functions for manipulation, string functions, date and time formatting, file handling, and object-oriented programming concepts including classes, objects, constructors, and destructors. The module emphasizes the advantages of OOP and provides examples for practical understanding.

Uploaded by

Leslie Qwer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

MODULE 2 PHP

MODULE 2

ARRAY

• An array is a data structure that stores one or more data values having some
relation among them, in a single variable.

• For example, if you want to store the marks of 10 students in a class, then
instead of defining 10 different variables, it’s easy to define an array of 10
length.

• Arrays in PHP behave a little differently than the arrays in C, as PHP is a


dynamically typed language as against C which is a statically type language.

• An array in PHP is an ordered map that associates values to keys.

• A PHP array can be used to implement different data structures such as a stack,
queue, list (vector), hash table, dictionary, etc.

• The value part of an array element can be other arrays. This fact can be used to
implement tree data structure and multidimensional arrays.

• There are two ways to declare an array in PHP.

• One is to use the built-in array() function, and the other is to use a shorter
syntax where the array elements are put inside square brackets.

• Creating an array
<?php
$cars = ["Volvo", "BMW", "Toyota"];
var_dump($cars);
?>

The array() Function

• The built-in array() function uses the parameters given to it and returns an object
of array type.

• One or more comma-separated parameters are the elements in the array.


• Each value in the parenthesis may be either a singular value (it may be a
number, string, any object or even another array), or a key-value pair.

• The association between the key and its value is denoted by the "=>" symbol.

1|Page
MODULE 2 PHP

Using Square Brackets [ ]


Instead of the array() function, the comma-separated array elements may
also be put inside the square brackets to declare an array object. In this case
too, the elements may be singular values or a string or another array.

Types of Arrays in PHP


• Indexed Array − An array which is a collection of values only is called an
indexed array. Each value is identified by a positional index staring from "0".
Values are stored and accessed in linear fashion.

• Associative Array − If the array is a collection of key-value pairs, it is called as


an associative array. The key component of the pair can be a number or a
string, whereas the value part can be of any type. Associative arrays store the
element values in association with key values rather than in a strict linear index
order.

• Multi-Dimensional Array − If each value in either an indexed array or an


associative array is an array itself, it is called a multi dimensional array. Values
are accessed using multiple indices.

PHP - Indexed Array

2|Page
MODULE 2 PHP

• In PHP, the array elements may be a collection of key-value pairs or it may


contain values only.
• If the array consists of values only, it is said to be an indexed array, as each
element is identified by an incrementing index, starting with "0".

• In PHP, an indexed array may be created using the array() function or the
square bracket syntax.

PHP - Associative Array

• If each element in a PHP array is a key-value pair, such an array is called an


associative array.

• In this type of array, each value is identified by its associated key and not an
index.
• Associative arrays are used to implement data structures such as dictionary,
maps, trees, etc.

• In PHP, the "=>" symbol is used to establish association between a key and its
value.

How to Declare an Associative Array in PHP?

• Both the approaches of declaring an array – the array() function and the square
bracket notation – can be used.

3|Page
MODULE 2 PHP

PHP - Multidimensional Array

• A multidimensional array is an array of arrays.


• In a PHP array, each element can be another array.
• If the array consists of values or key-value pairs with values being of singular
scalar types, it is a one-dimensional array.

• If each element in an array is an array of one or more scalar values, it is a


twodimensional array.

• A PHP array may be a two-dimensional associative array also, where each


element of the outer array is key-value pair, the value being another associative
array.

4|Page
MODULE 2 PHP

PHP Array Functions

PHP Array Functions allow to interact with and manipulate arrays in various ways.
PHP arrays are essential for storing, managing, and operating on sets of variables.

PHP supports simple and multi-dimensional arrays and may be either user created
or created by another function.

Function Description

array() Creates an array

array_change_key_case() Changes all keys in an array to lowercase or uppercase

array_chunk() Splits an array into chunks of arrays

5|Page
MODULE 2 PHP

array_column() Returns the values from a single column in the input array

array_combine() Creates an array by using the elements from one "keys" array and one "va
array

array_count_values() Counts all the values of an array

array_diff() Compare arrays, and returns the differences (compare values only)

array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)

array_diff_key() Compare arrays, and returns the differences (compare keys only)

array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, u
user-defined key comparison function)

array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a
defined key comparison function)

array_fill() Fills an array with values

array_fill_keys() Fills an array with values, specifying keys

array_filter() Filters the values of an array using a callback function

array_flip() Flips/Exchanges all keys with their associated values in an array

array_intersect() Compare arrays, and returns the matches (compare values only)

array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)

6|Page
MODULE 2 PHP

array_intersect_key() Compare arrays, and returns the matches (compare keys only)

array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, usin
defined key comparison function)

array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a
use key comparison function)

array_key_exists() Checks if the specified key exists in the array

array_keys() Returns all the keys of an array

array_map() Sends each value of an array to a usermade function, which returns new

array_merge() Merges one or more arrays into one array

PHP String Functions

The PHP string functions are part of the PHP core. No installation is required to use
these functions.

strrpos() Finds the position of the last occurrence of a string inside another string
(casesensitiv

strspn() Returns the number of characters found in a string that contains only characters
from specified charlist

strstr() Finds the first occurrence of a string inside another string (case-sensitive)

strtok() Splits a string into smaller strings

7|Page
MODULE 2 PHP

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters

strtr() Translates certain characters in a string

substr() Returns a part of a string

substr_compare() Compares two strings from a specified start position (binary safe and optionally case

substr_count() Counts the number of times a substring occurs in a string

substr_replace() Replaces a part of a string with another string

Formatting Strings

PHP String sprintf() function

• The sprintf() is an in-built function of PHP which writes a formatted string to a


variable.

• It returns a formatted string.

8|Page
MODULE 2 PHP

• The sprintf() function is similar to the printf() function, but the only difference
between both of them is that sprint() saves the output into a string instead of
displaying the formatted message on browser like printf() function.

• The sprintf() works with echo.


• The formatted string returns by the sprintf() function is printed by echo on the
browser whereas printf() directly put the output on browser.

Syntax

sprintf (format, agr1, agr2, arg3...) : string

PHP Date and Time

The PHP date() function is used to format a date and/or a time.

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and

time. Syntax

date(format,timestamp)

9|Page
Parameter Description

MODULE 2 PHP
format Required. Specifies the format of the timestamp

timestamp Optional. Specifies a timestamp. Default is the current date and time

A timestamp is a sequence of characters, denoting the date and/or time at which a


certain event occurred

Get a Date

The required format parameter of the date() function specifies how to format the
date (or time).

Here are some characters that are commonly used for dates:

• d - Represents the day of the month (01 to 31)

• m - Represents a month (01 to 12)

• Y - Represents a year (in four digits)

• l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to
add additional formatting.

<?php
echo "Today is " .
date("Y/m/d") . "<br>"; echo
"Today is " . date("Y.m.d") .
"<br>"; echo "Today is " .
date("Y-m-d") . "<br>"; echo
"Today is " . date("l"); ?>

Get a Time

Here are some characters that are commonly used for times:

10 | P a g e
MODULE 2 PHP

• H - 24-hour format of an hour (00 to 23)

• h - 12-hour format of an hour with leading zeros (01 to 12)

• i - Minutes with leading zeros (00 to 59)

• s - Seconds with leading zeros (00 to 59)

• a - Lowercase Ante meridiem and Post meridiem (am or pm)

Example

<?php
echo "The time is ".
date("h:i:sa"); ?>

File open modes

When opening a file, several different modes can be used. The most common
ones are r and w for read and write. There are several more available, though,
that will control whether to create a new file, open an existing file, and start
writing at the beginning or the end. These modes are used with open () in the
rest of the examples.

• r - read only

• w - write only, force new file

• a - write only with pointer at end

• x - write only, create new file or error on existing

• r+ - read/write, file pointer at beginning

• w+ - read/write, force new file

• a+ - read/write, file pointer at end


• x+ - read/write, create new file or error on existing

Write to a file

When writing files, we have two primary options that we will look at:

11 | P a g e
MODULE 2 PHP

• Writing bytes as needed with fwrite()

• Writing the entire file contents at once with file_put_contents()

Read from a file

When reading a file we have the same two primary options that we will look at:
• Reading bytes as needed with fread()
• Reading the entire file in to a variable with file_get_contents()
Common file tasks

Here are some examples of other common tasks I perform with files like:

• Getting file size


• Checking if a file exists
• Check if a file is a directory
• Get a lock on a file
• Read and write JSON

Get filesize
It can quickly get the size of a file in bytes using the filesize() function.

<?php

echo filesize('hello.txt');

?>

Check if file exists


It can easily check if a file exists with the file_exists() function.

<?php

echo file_exists('hello.txt');

?>
Check if file is a directory - you can use is_dir() function.
Get current working directory - you can use getcwd() function.

Change directory - you can use chdir() function.

Make directory - can make a directory with mkdir().

Remove directory - delete a directory with rmdir().

Get directory contents

If we want to list the contents of a directory you have two main options:

12 | P a g e
MODULE 2 PHP

• scandir() - scandir() will return all contents of a directory

• glob() - glob() lets you search for contents in a directory using a pattern like *.* or *.png

PHP OOP
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or functions that perform operations
on the data, while object-oriented programming is about creating objects that contain both
data and functions.

Object-oriented programming has several advantages over procedural programming:


• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and shorter
development time.
• The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code.

PHP - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.

So, a class is a template for objects, and an object is an instance of a class.


When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
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

13 | P a g e
MODULE 2 PHP

class Fruit {
// code goes here...
}
?>

Example

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
{ //
Prop
erties
publi
c
$nam
e;
publi
c
$colo
r; //
Meth
ods

function set_name($name) {
$this->name = $name;
}
function
get_name() {
return $this-
>name;

}
}
?>

14 | P a g e
MODULE 2 PHP

Note: In a class, variables are called properties and functions are called

methods.

Object: A class defines an individual instance of the data structure. We define

a class once and then make many objects that belong to it. Objects are also

known as an instance.

An object is something that can perform a set of related activities.


Syntax:

<?php

class

MyCla

ss

{
// Class properties and methods go here
}
$obj = new MyClass;

var_dump($obj);

?>

Example of class and object:

<?

ph

cla

ss

de

mo

15 | P a g e
MODULE 2 PHP

private $a= "hello

javatpoint"; public

function display()

{
echo $this->a;
}
}
$obj = new demo();
$obj->display();
?>

Constructor and Destructor

 In object-oriented programming, both constructor and destructor are the member


functions of a class having the same name as the class.
 A constructor helps in the initialization of an object, i.e., it allocates memory to
an object.
 On the other hand, a destructor deletes the created constructor when it is of no use which
means it de-allocates the memory of an object.

What is a Constructor?
 A constructor is a member function of a class that initializes the object and allocates the
memory.
 A constructor has the same name as that of its class, thus it can be easily
identified.
 It is always declared and defined in the public section of a class. A constructor
does not have any return type.
 Therefore, it does not return anything, but it is not even void.
Syntax:
Class_name (arguments if any)
{


};

16 | P a g e
MODULE 2 PHP

A single class may have multiple constructors that are differentiated based on the number
and
type of arguments passed. There are three main types of constructors, namely, default
constructor, parameterized constructor, and copy constructor.

Example 1

<?php
Class Example
{
Public function __construct()
{
Echo “Hello”;
}
}
$obj = new Example();
$obj = new Example();
?>

What is a Destructor?

• A destructor is a member function of a class that deallocates the


memory allocated to an object.
• A destructor is also declared and defined with the same name as that of
the class.

• A destructor is preceded by a tilde (~) symbol. A single class has only a


single destructor.

Class_name (no arguments)

};

17 | P a g e
MODULE 2 PHP

A destructor does not have any argument and is always called in the reverse
order of the constructor. Destructor are required for destroying the objects to
release the memory allocated to them.

Example 1
<?php
class demo
{
public function demo()
{
echo “constructor1…”;
}
}
class demo1 extends demo
{
public function __construct()
{
echo parent::demo();
echo “constructor2…”;
}
public function __destruct()
{
echo “destroy…..”;
}
}
$obj= new demo1();
?>

18 | P a g e
MODULE 2 PHP
CONSTUCTOR DESTRUCTOR

Constructors help allocate memory to an Destructors deallocate the memory of an


object.
object.

Constructors can take arguments. Destructors don’t take any arguments.

Constructors are called automatically when an Destructors are called automatically when the
object is created. block is exited or when the program
terminates.

Constructors allow an object to initialize a They allow objects to execute code when it is
value before it is used. being destroyed.

They are called in the successive order of They are called in the reverse order of their
their creation. creation.

There can be multiple constructors in a single There is a single destructor in a class.


class.

Constructors can be overloaded. Destructors cannot be overloaded.

The concept of copy constructor allows an There is no such concept in the case of
object to get initialized from another object. destructors.

Difference between Abstract class and Interfaces.

Abstract class:

 Abstract class comes under partial abstraction.


 Abstract classes can maintain abstract methods and non abstract methods.
 In abstract classes, we can create the variables.
 In abstract classes, we can use any access specifier.
 By using ‘extends’ keyword we can access the abstract class features from derived class.
 Multiple inheritance is not possible.

Interface:

 Interface comes under fully abstraction.


 Interfaces can maintain only abstract methods.
 In interfaces, we can’t create the variables.
 In interface, we can use only public access specifier.
 By using ‘implement’ keyword we can get interface from derived class.
 By using interfaces multiple inheritance is possible.

Inheritance:

19 | P a g e
MODULE 2 PHP

• Inheritance is one of the fundamental principles of object-oriented programming.


• Inheritance is a software modeling approach that enables extending the capability of an
existing class to build a new class instead of building from scratch.
• PHP provides all the functionality to implement inheritance in its object model.
• It is a concept of accessing the features of one class from another class.
• If we inherit the class features into another class, we can access both class properties.
• We can extend the features of a class by using the ‘extends’ keyword.
• It supports the concept of hierarchical classification.
• Inheritance has three types, single, multiple and multilevel Inheritance.
• PHP supports only single inheritance, where only one class can be derived from single
parent class.
• We can simulate multiple inheritance by using interfaces.

Example 1

<?php
Class a
{
function fun1()
{
echo “javatpoint”;
}
}
class b extends a
{
function fun2()
{
echo “SSSIT”;
}
}
$obj= new b();
$obj->fun1();

?>

PHP – Access Modifiers

 In PHP, the keywords public, private and protected are known as the access
modifiers.
 These keywords control the extent of accessibility or visibility of the class
properties and methods.

20 | P a g e
MODULE 2 PHP

 One of these keywords is prefixed while declaring the member variables and
defining member functions.

Whether the PHP code has free access to a class member, or it is restricted
from getting access, or it has conditional access, is determined by these
keywords –

• Public – class members are accessible from anywhere, even from


outside the scope of the class, but only with the object reference.
• Private – class members can be accessed within the class itself. It
prevents members from outside class access even with the reference of
the class instance.
• Protected – members can be accessed within the class and its child
class only, nowhere else.

EXAMPLE 1: Public

<?php
class Demo
{
public $name = "Ajeet";
function disp()
{
echo $this->name . "<br/>";
}
}
class Child extends Demo
{
function show() Output
{
echo $this->name;
}
}
$obj = new Child();
echo $obj->name . "<br/>";
$obj->disp();
$obj->show();
?>

21 | P a g e
MODULE 2 PHP

EXAMPLE 2: Private

<?php
class Hello
{
private $name = "Sonoo";
private function show()
{
echo "This is a private method of the parent class.<br/>";
}
}
class Child extends Hello
{
public function show1()
{
echo "Cannot access private property of the parent class.<br/>";
}
} output
$obj = new Child();
$obj->show1();
?>

EXAMPLE 3: Protected

<?php
class Hello
{
protected $x = 500;
protected $y = 100;
function add()
{
echo $this->x + $this->y . "<br/>";
}
} output
class Child extends Hello
{
function sub()
{
echo $this->x - $this->y . "<br/>";
}
}
$obj = new Child();
$obj->add();
$obj->sub();
?>

22 | P a g e
MODULE 2 PHP

PHP – Constants

A constant in PHP is a name or an identifier for a simple value. A constant value cannot change
during the execution of the PHP script.

 By default, a PHP constant is case-sensitive.


 By convention, constant identifiers are always uppercase.
 A constant name starts with a letter or underscore, followed by any number of letters,
numbers, or underscore.
 There is no need to write a dollar sign ($) before a constant, however one has to use a
dollar sign before a variable.

Examples of Valid and Invalid Constant Names in PHP

// Valid constant names

Define(“ONE”, “first thing”);

Define(“TWO2”, “second thing”);

Define(“THREE_3”, “third thing”);

Define(“__THREE__”, “third value”);

// Invalid constant names

Define(“2TWO”, “second thing”);

PHP constants can be defined by 2 ways:

1. Using define() function


2. Using const keyword
.
Constants are similar to the variable except once they defined, they can never be undefined or
changed. They remain constant across the entire program. PHP constants follow the same PHP
variable rules. For example, it can be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

Note: Unlike variables, constants are automatically global throughout the script.

23 | P a g e
MODULE 2 PHP

PHP constant: define()

Use the define () function to create a constant. It defines constant at run time.

Syntax:

define (name, value, case-insensitive)

1. Name: It specifies the constant name.

2. Value: It specifies the constant value.


3. Case-insensitive: Specifies whether a constant is case-insensitive. The default value
is false. It means it is case-sensitive by default.

File: constant1.php

<?php

define(“MESSAGE”, “Hello PHP”);

echo MESSAGE;

?>

Traits in PHP

PHP only supports single inheritance: a child class can inherit only from one single parent.

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:

24 | P a g e
MODULE 2 PHP

Syntax:

<?php
trait traitname {
// some code…
}
?>

To use a trait in a class, use the use keyword:

Syntax

<?php
class MyClass {
use TraitName;
}
?>

PHP – Static Methods

 Static methods can be called directly – without creating an instance of the class first.
 Static methods are declared with the static keyword:
 The “static” keyword in PHP defines static properties and methods in a PHP class.
 It may also be noted that the static keyword defines static variables and static
anonymous functions.
 The syntax of a static method call is

class ClassName {
public static function methodName() {
// Code for the static method
}
}
Example
<?php
class Greeting
{
public static function welcome() output
{
echo "Hello World!";
}
}

25 | P a g e
MODULE 2 PHP

// Call static method


Greeting::welcome();
?>

PHP – Static Properties

 Static properties can be called directly – without creating an instance of a class.


 Static properties are declared with the static keyword:

Syntax

To access a static property use

ClassName::$staticProperty;

Example
<?php
class Pi output
{
public static $value = 3.14159;
}
// Get static property
echo Pi::$value;
?>

PHP – Namespaces

 In PHP, namespaces allow classes, functions, or constants of the same


name to be used in different contexts without conflict, thereby encapsulating
these items.
 A PHP namespace is a logical grouping of classes/functions etc., depending
on their relevance.
 Just as a file with the same name can exist in two different folders, a class of
a certain name can be defined in two namespaces.
 Further, specify the complete path of a file to gain access, we need to specify
the full name of the class along with the namespace.

Advantages of Namespace

 Namespaces help in avoiding name collisions between classes/functions/constants


defined by someone with third-party classes/functions/constants.

26 | P a g e
MODULE 2 PHP

 Namespaces provide the ability to alias (or shorten) Extra_Long_Names, thereby


improving the readability of source code.
 PHP Namespaces provide a way in which to group related classes, interfaces,
functions and constants. Namespace names are case – insensitive.

Defining a Namespace

PHP’s namespace keyword is used to define a new namespace.

namespace myspace;

A “.php” file containing a namespace must declare the namespace at the top of
the file before any other (except the declare directive). Declaration of class,
function and constants inside a namespace affects its access.

PHP – What is an Iterable?

 An iterable is any value that can be looped through with a foreach() loop.
 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 – Using Iterables - The iterable keyword can be used as a data type of a function argument
or as the return type of a function:
Example :
<?php
function printIterable(iterable $myIterable) { output
foreach ($myIterable as $item) {
echo $item . "<br/>";
}
}
$arr = ["a", "b", "c"];
printIterable($arr);
?>

27 | P a g e

You might also like