Unit 4
Unit 4
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
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
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;
To create an object from a class, use the new keyword followed by the class name and a
pair of parentheses.
• 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 = [];
•Invoked when calling isset() or empty() on inaccessible (protected or private) or non-existing properties.
class MyClass {
private $data = [];
class MyClass {
private $data = [];
$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.
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
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
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:
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:
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:
• 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
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;
}
} }
?>
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();
// 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() { }
// Usage
$child1 = new ChildClass1();
$child1->grandparentMethod(); // Method from Grandparent
class
$child1->parentMethod(); // Method from Parent class
$child1->childMethod1(); // Method from ChildClass1
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