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

Unit 4

Uploaded by

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

Unit 4

Uploaded by

anavadeepcs
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

TITLE LOREM IPSUM

SIT DOLOR AMET


PHP WHAT IS 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
WHAT ARE CLASSES AND OBJECTS?

a class is a blueprint for creating objects. It defines a set of properties and methods to be
used by the objects created from the class. An object is an instance of a class, which
means it has its own set of properties and methods defined in the class.
DECLARING A CLASS

Classes are the blueprints of objects(or) Class is a collection of objects(or) Wrapping up


of the data and associated methods into a single unit is called class. A class can be
declared using the class keyword, followed by the name of the class and a pair of curly
braces ({}).
Syntax
<?php
class Fruit {
// code goes here...
}
?>
EXAMPLE
<?php
class GeeksforGeeks
{
public function __construct()
{
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
}
$obj = new GeeksforGeeks;
?>
Output: The class "GeeksforGeeks" was initiated.
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,

 Objects of a class are created using the new keyword.


 <?php
class Fruit {
// Properties
public $name;
public $color;

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

$apple = new Fruit();


$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
DEFINING PROPERTIES AND METHODS

 Properties are variables that belong to a class, and methods are functions that belong
to a class. To define properties, use the public, private, or protected keyword followed
by the property name. Similarly, to define methods, use the public, private, or
protected keyword followed by the method name and a pair of parentheses.
class MyClass {
public $property1;
private $property2;
protected $property3;

public function method1() {


// Code goes here
}

private function method2() {


// Code goes here
}

protected function method3() {


// Code goes here
}
}
CREATING AN OBJECT

To create an object from a class, use the new keyword followed by the class name and a
pair of parentheses.

$object1 = new MyClass();


Creating an Object:
Following is an example of how to create object using new operator.
class Book {
// Members of class Book
}
// Creating three objects of book
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Member Functions:
After creating our objects, we can call member functions related to that object. A member function
typically accesses members of current object only.
Example:
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Defining Class Methods
Methods are class-specific functions. Individual actions that an object will be able to perform are
defined within the class as methods. public function getProperty()
{
<?php return $this->prop1 . "<br />";
class MyClass }
}
{ $obj = new MyClass;
echo $obj->getProperty(); // Get the property value
public $prop1 = "I'm a class property!"; $obj->setProperty("I'm a new property value!"); // Set a new
public function setProperty($newval) one
echo $obj->getProperty(); // Read it out again to show the
{ change
?>
$this->prop1 = $newval; Output: I'm a class property!
} I'm a new property value!
Example:
<?php
function setTitle($par)
class Books { {
/* Member variables */ $this->title = $par;
}
var $price; function getTitle(){
var $title; echo $this->title."<br>" ;
}
/* Member functions */ }
function setPrice($par){ /* Creating New object using "new" operator */
$maths = new Books;
$this->price = $par; /* Setting title and prices for the object */
$maths->setTitle( "Algebra" );
}
$maths->setPrice( 7 );
function getPrice(){ /* Calling Member Functions */
$maths->getTitle();
echo $this->price."<br>";
$maths->getPrice();
} ?>
OVERLOADING

 overloading refers to the ability to dynamically create properties and methods.


However, it's important to note that PHP's version of overloading is different from
traditional method overloading seen in languages like Java or C++, where you can
define multiple methods with the same name but different parameters. In PHP,
overloading allows you to handle the interactions with properties and methods that
are not explicitly declared within a class.
PROPERTY AND RULES OF OVERLOADING IN PHP:

• All overloading methods must be defined as Public.


• After creating the object for a class, we can access a set of entities that are properties or methods not
defined within the scope of the class.
• Such entities are said to be overloaded properties or methods, and the process is called as overloading.
• For working with these overloaded properties or functions, PHP magic methods are used.
• Most of the magic methods will be triggered in object context except __callStatic() method which is
used in a static context.
TYPES OF OVERLOADING IN PHP:

 There are two types of overloading in PHP.

• Property Overloading
• Method Overloading
PROPERTY OVERLOADING:

 PHP property overloading is used to create dynamic properties in the object context. For creating these
properties no separate line of code is needed. A property associated with a class instance, and if it is not
declared within the scope of the class, it is considered as overloaded property.
MAGIC METHODS

PHP supports overloading through the use of magic methods, which are special methods that begin with
double underscores (__).
• __set(): triggered while initializing overloaded properties.
• __get(): triggered while using overloaded properties with PHP print statements.
• __isset(): This magic method is invoked when we check overloaded properties with isset() function
• __unset(): Similarly, this function will be invoked on using PHP unset() for overloaded properties.
THE __SET() METHOD IS AUTOMATICALLY CALLED WHEN YOU ATTEMPT TO SET THE VALUE OF
AN INACCESSIBLE OR NON-EXISTENT PROPERTY IN AN OBJECT.
_set($name, $value): _Invoked when writing data to inaccessible (protected or private) or
non-existing properties.
class MyClass {
private $data = [];

public function __set($name, $value) {


$this->data[$name] = $value;
}}
$obj = new MyClass();
$obj->property = 'value'; // Calls __set('property', 'value')
__get() magic method in PHP is a special method that is automatically invoked when you attempt to
access a property that is not publicly accessible or does not exist within the object. It allows you to
dynamically handle the retrieval of such properties.
a class MyClass with a private property $data (an array), and a __get magic method to handle
attempts to read inaccessible or non-existent properties.
class MyClass {
private $data = [];
public function __get($name)
{
return $this->data[$name] ?? null;
}}
$obj = new MyClass();
echo $obj->property; // Calls __get('property')
The isset() function in PHP is used to determine if a variable is set and is not null. It is commonly used to check if
a variable or an array key exists before performing operations on it__isset($name) :

•Invoked when calling isset() or empty() on inaccessible (protected or private) or non-existing properties.

class MyClass {
private $data = [];

public function __isset($name) {


return isset($this->data[$name]);
}
}

$obj = new MyClass();


isset($obj->property); // Calls __isset('property')
How isset() Works
Returns true if the variable exists and is not null.
Returns false if the variable does not exist or is null.
Example :
Checking a Single Variable:
$a = "Hello, world!";
if (isset($a)) {
echo "Variable 'a' is set.";
} else {
echo "Variable 'a' is not set.";
}
// Output: Variable 'a' is set.
unset() function in PHP is used to destroy a given variable. This means that after using unset(), the variable will
no longer be set and attempting to use it will result in an undefined variable error. __unset($name) :
•Invoked when unset() is used on inaccessible (protected or private) or non-existing properties.

class MyClass {
private $data = [];

public function __unset($name) {


unset($this->data[$name]);
}
}

$obj = new MyClass();


unset($obj->property); // Calls __unset('property')
EXAMPLE : UNSETTING A SINGLE VARIABLE

$a = "Hello, world!";
echo $a; // Outputs: Hello, world!
unset($a);
echo $a; // Throws a notice: Undefined variable: a
METHOD OVERLOADING:

 It is a type of overloading for creating dynamic methods that are not declared within the class scope.
PHP method overloading also triggers magic methods dedicated to the appropriate purpose. Unlike
property overloading, PHP method overloading allows function call on both object and static context.
The related magic functions are,
• __call() – triggered while invoking overloaded methods in the object context.
• __callStatic() – triggered while invoking overloaded methods in static context.
__CALL() IS TRIGGERED WHEN INVOKING INACCESSIBLE METHODS IN AN OBJECT CONTEXT.

__CALLSTATIC() IS TRIGGERED WHEN INVOKING INACCESSIBLE METHODS IN A STATIC CONTEXT.

THE $NAME ARGUMENT IS THE NAME OF THE METHOD BEING CALLED.

THE $ARGUMENTS ARGUMENT IS AN ENUMERATED ARRAY CONTAINING THE PARAMETERS PASSED TO THE $NAME'ED METHOD.
 <?php
class MethodTest
{
public function __call($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
public static function __callStatic($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
} Output :
$obj = new MethodTest; Calling object method 'runTest' in object context
$obj->runTest('in object context'); Calling static method 'runTest' in static context

MethodTest::runTest('in static context');


?>
__construct Function
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create an object
from a class.
<?php
class Fruit {
public $name;
public $color;

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

$apple = new Fruit("Apple");


echo $apple->get_name();
?>
destructor
A destructor is called when the object is destructed or the script is stopped or
exited.If you create a __destruct() function, PHP will automatically call this
function at the end of the script.
<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");


?>
HTTP GET AND HTTP GET AND POST METHODS IN PHP
METHODS IN PHP

 HTTP: The Hypertext Transfer Protocol (HTTP) is designed to enable communications between
clients and servers. HTTP works as a request-response protocol between a client and server. A web
browser may be the client, and an application on a computer that hosts a website may be the server. A
client (browser) submits an HTTP request to the server; then the server returns a response to the client.
 There are 2 HTTP request methods:

• GET: Requests data from a specified resource.


• POST: Submits data to be processed to a specified resource.
GET METHOD:

In the GET method, the data is sent as URL parameters that are usually strings of name and value pairs
separated by ampersands (&). In general, a URL with GET data will look like this:

Example: Consider the below example:

http://www.example.com/action.php?name=Sam&weight=55
Here, the bold parts in the URL denote the GET parameters and the italic parts denote the value of those
parameters. More than one parameter=value can be embedded in the URL by concatenating with
ampersands (&)
<?php
error_reporting(0);
if( $_GET["name"] || $_GET["weight"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['weight']. " kgs in weight.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Weight:<input type="text" name="weight" />
<input type="submit" />
</form>
</body>
</html>
 Advantages:

• Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page
with specific query string values.
• GET requests can be cached and GET requests to remain in the browser history.
 Disadvantages:

• The GET method is not suitable for passing sensitive information such as the username and password,
because these are fully visible in the URL query string as well as potentially stored in the client
browser’s memory as a visited page.
POST METHOD:

In the POST method, the data is sent to the server as a package in a separate communication with the
processing script. Data sent through the POST method will not be visible in the URL.
Consider the below example:

POST /test/demo_form.php HTTP/1.1


Host: gfs.com
SAM=451&MAT=62
The query string (name/weight) is sent in the HTTP message body of a POST request.
 Advantages:

• It is more secure than GET because user-entered information is never visible in the URL query string
or in the server logs.
• There is a much larger limit on the amount of data that can be passed and one can send text data as
well as binary data (uploading a file) using POST.

 Disadvantages:

• Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the
page with a specific query.
• POST requests are never cached
HTML FORMS

 HTML forms are used to send the user information to the server and returns the result back to the
browser.

For example, if you want to get the details of visitors to your website, and send them good thoughts, you
can collect the user information by means of form processing. Then, the information can be validated
either at the client-side or on the server-side. The final result is sent to the client through the respective
web browser.
ATTRIBUTES OF FORM TAG:

Attribute Description
name or id It specifies the name of the form and is used to identify individual forms.

It specifies the location to which the form data has to be sent when the form is
action
submitted.

It specifies the HTTP method that is to be used when the form is submitted. The
method possible values are get and post. If get method is used, the form data are visible
to the users in the url. Default HTTP method is get.

encType It specifies the encryption type for the form data when the form is submitted.

novalidate It implies the server not to verify the form data when the form is submitted.
CONTROLS USED IN FORMS: FORM PROCESSING CONTAINS A SET OF CONTROLS
THROUGH WHICH THE CLIENT AND SERVER CAN COMMUNICATE AND SHARE
INFORMATION. THE CONTROLS USED IN FORMS ARE:

• Textbox: Textbox allows the user to provide single-line input, which can be used for getting values
such as names, search menu and etc.
• Textarea: Textarea allows the user to provide multi-line input, which can be used for getting values
such as an address, message etc.
• DropDown: Dropdown or combobox allows the user to provide select a value from a list of values.
• Radio Buttons: Radio buttons allow the user to select only one option from the given set of options.
• CheckBox: Checkbox allows the user to select multiple options from the set of given options.
• Buttons: Buttons are the clickable controls that can be used to submit the form.
INHERITANCE

inheritance is a fundamental object-oriented programming concept in PHP where a class


(subclass or child class) can inherit properties and methods from another class (superclass or parent
class). It enables code reusability and promotes hierarchical relationships between classes.
Syntax:
// Parent class
class Animal {
public $species; // Child class inheriting from
Animal
class Dog extends Animal {
public function sound() { public function sound() {
return "Dog barks.";
return "Animal makes a sound."; }
}
}
}
Accessing Parent Class Members:
•Child classes can access parent class properties and methods using
the parent:: keyword.

Constructor in Inheritance:
•Child classes can have their own constructors, which can optionally call the parent
class constructor using parent::__construct( ).
Different Types of Inheritance
OOPs support the six different types of inheritance as given below :
Single inheritance
In this inheritance, a derived class is created from a single base class.In the given
example, Class A is the parent class and Class B is the child class since Class B inherits
the features and behavior of the parent class A.
Syntax for Single Inheritance
//Base Class
//Derived Class
class A class B : A
{ {
public void fooB()
public void fooA() {
{ //TO DO:
}
//TO DO: }
}
}
 <?php class Bar extends Foo
{
class Foo public function printItem($string)
{ {
public function printItem($string) echo 'Bar: ' . $string . PHP_EOL;
{
echo 'Foo: ' . $string . PHP_EOL;
}
} }

public function printPHP() $foo = new Foo();


{ $bar = new Bar();
echo 'PHP is great.' . PHP_EOL;
$foo->printItem('baz'); // Output: 'Foo:
}
} baz'
$foo->printPHP(); // Output: 'PHP is great'

$bar->printItem('baz'); // Output: 'Bar:


baz'
$bar->printPHP(); // Output: 'PHP is great'

?>
Multi-level inheritance
In this inheritance, a derived class is created from another derived class.
In the given example, class c inherits the properties and behavior of class B and
class B inherits the properties and behavior of class B. So, here A is the parent class
of B and class B is the parent class of C. So, here class C implicitly inherits the
properties and behavior of class A along with Class B i.e there is a multilevel of
inheritance.
}
Syntax for Multi-level Inheritance //Derived Class
class B : A
//Base Class {
public void fooB()
class A
{
{ //TO DO:
}
public void fooA()
}
{ //Derived Class
class C : B
//TO DO: {
} public void fooC()
{
//TO DO:
}
}
<?php // Further derived class
class Child extends ParentClass {
// Base class public function showChild() {
class Grandparent { echo "This is the Child class, derived from ParentClass.\n";
}
public function showGrandparent() { }

echo "This is the Grandparent class.\n"; // Create an instance of the Child class
} $child = new Child();

} // Call methods from all three classes


$child->showGrandparent(); // Method from Grandparent class
$child->showParent(); // Method from ParentClass
$child->showChild(); // Method from Child class
// Derived class
?>
class ParentClass extends Grandparent {
public function showParent() {
echo "This is the Parent class, derived from Grandparent.\n";
}
Hierarchical Inheritance
 In this inheritance, more than one derived classes are created from a single base class
 and futher child classes act as parent classes for more than one child classes.
 In the given example, class A has two childs class B and class D. Further, class B and class
 C both are having two childs - class D and E; class F and G respectively.
<?php
// Derived class 2
// Base class class ChildClass2 extends ParentClass {
class ParentClass { public function childMethod2() {
echo "This is a method from ChildClass2.\n";
public function parentMethod() { }
}
echo "This is a method from the Parent class.\n";
} // Usage
$child1 = new ChildClass1();
}
$child1->parentMethod(); // Method from Parent class
$child1->childMethod1(); // Method from ChildClass1
// Derived class 1 $child2 = new ChildClass2();
class ChildClass1 extends ParentClass { $child2->parentMethod(); // Method from Parent class
$child2->childMethod2(); // Method from ChildClass2
public function childMethod1() { ?>
echo "This is a method from ChildClass1.\n";
}
}
Multiple inheritance
In this inheritance, a derived class is created from more than one base class. This
inheritance is not supported by .NET Languages like C#, F# etc. and Java Language.
In the given example, class c inherits the properties and behavior of class B and class A
at same level. So, here A and Class B both are the parent classes for Class C.
PHP achieves a similar effect using traits. Traits allow you to reuse sets of methods freely in
several classes. Here’s how you can use traits to implement something similar to multiple
inheritance in PHP
<?php // Define a class that uses both traits
// Define a trait for one set of methods class CombinedClass {
use TraitA, TraitB;
trait TraitA {
public function methodA() { public function combinedMethod() {
echo "This is a method from CombinedClass.\n";
echo "This is methodA from TraitA.\n"; }
} }

} // Create an instance of the CombinedClass


$combined = new CombinedClass();

// Define another trait for another set of methods // Call methods from both traits and the class itself
$combined->methodA(); // Method from TraitA
trait TraitB { $combined->methodB(); // Method from TraitB
public function methodB() { $combined->combinedMethod(); // Method from
CombinedClass
echo "This is methodB from TraitB.\n"; ?>
}
}
Hybrid (or Virtual) Inheritance
A combination of two or more types of inheritance. For instance, a combination of multilevel and
hierarchical inheritance.
<?php // Derived class 1
class ChildClass1 extends ParentClass {
// Base class public function childMethod1() {
class Grandparent { echo "This is a method from ChildClass1.\n";
}
public function grandparentMethod() { }

echo "This is a method from the Grandparent class.\n";


}
}
// Intermediate class
class ParentClass extends Grandparent {
public function parentMethod() {
echo "This is a method from the Parent class.\n";
}
}
// Derived class 2
class ChildClass2 extends ParentClass {
public function childMethod2() {
echo "This is a method from ChildClass2.\n";
}
}

// Usage
$child1 = new ChildClass1();
$child1->grandparentMethod(); // Method from Grandparent
class
$child1->parentMethod(); // Method from Parent class
$child1->childMethod1(); // Method from ChildClass1

$child2 = new ChildClass2();


$child2->grandparentMethod(); // Method from Grandparent
class
$child2->parentMethod(); // Method from Parent class
$child2->childMethod2(); // Method from ChildClass2
?>
Advantages of Inheritance

1. Reduce code redundancy.


2. Provides code reusability.
3. Reduces source code size and improves code readability.
4. The code is easy to manage and divided into parent and child classes.
5. Supports code extensibility by overriding the base class functionality
within child
classes.
DATE & TIME FUNCTIONS

Function
checkdate() Validates set of Gregorian year, month, and day values (for example,
2005, 3, 17).
date_sunrise() Returns time of sunrise for a given day and location (new in PHP 5).
date_sunset() Returns time of sunset for a given day and location (new in PHP 5).
date() Formats a local date/time, given a Unix timestamp (for example,
1111035030000 ) and a formatting string.
getdate() Given a Unix timestamp, returns an associative array containing date and
time information (defaults to current time).
gettimeofday() Returns an associative array containing information about the current
system time.
Formatting Characters for the date() Function
Month
F Full name of the month (January, February, and so on).
M Three-letter abbreviation for the month (Jan, Feb, and so on).
m Numeric representation for the month, with leading zero (two digits).
n Numeric representation for the month (no leading zero).
Day
d Day of the month, with leading zeros (two digits).
j Day of the month (no leading zeros).
S Ordinal suffix for the day of the month, two characters (st, nd, th); most
commonly used in combination with j.
l (lowercase L) Full name of the day of the week (Monday, Tuesday, and so on).
D A textual representation of a day, three letters (Mon, Tue, and so on).
w Numeric representation of the day of the week (0 = Sunday, 6 = Saturday).
Year
y Two-digit year.
Y Four-digit year.
Hour
h Hour in 12-hour format, with leading zero (two digits).
g Hour in 12-hour format (no leading zero).
H Hour in 24-hour format, with leading zero (two digits).
Getting the Day and Week of the Year
 Obtaining the day of the year is fairly simple; you need use only a lowercase z in the first
argument to the date() function.
Example4:<?php
$mydates = array('2005-01-01', '2005-06-30', '2005-12-31');
foreach($mydates as $mydate)
{
$ts = strtotime($mydate);
echo 'Day ' . date('d M Y: z', $ts) . "<br />\n";
}
?>Output:
01 Jan 2005: Day 0
30 Jun 2005: Day 180
31 Dec 2005: Day 364
Determining the number of days in the current month
 We are using date(‘t’) function for finding number of days in a month.
 For finding number of days in current months we use both date(‘t’) and date(‘M’)
functions.
Example8:
<?php
echo 'Number of days for the month of '.date('M'). ' is :' .date('t')."\n";
?>
Output:
Number of days for the month of Sep is: 30
Access Modifier allows you to alter the visibility of any class member(properties and method).
In php there are three scopes for class members.
 Public
 Protected and
 Private
 Public Access modifier:

Public access modifier is open to use and access inside the class definition as well as outside the class
definition.
TITLE LOREM IPSUM DOLOR SIT AMET

Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet

2017 2018 2019

Lorem ipsum dolor sit amet

You might also like