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

Php unit 4 nep[1]

The document provides an overview of classes and objects in PHP, including how to create and access them, as well as their properties and methods. It explains form handling using PHP superglobals $_GET and $_POST, and covers concepts like constructors, destructors, and access modifiers. Additionally, it discusses method and property overloading in PHP, demonstrating how to use magic methods for dynamic property and method creation.

Uploaded by

vinaykavinayka7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Php unit 4 nep[1]

The document provides an overview of classes and objects in PHP, including how to create and access them, as well as their properties and methods. It explains form handling using PHP superglobals $_GET and $_POST, and covers concepts like constructors, destructors, and access modifiers. Additionally, it discusses method and property overloading in PHP, demonstrating how to use magic methods for dynamic property and method creation.

Uploaded by

vinaykavinayka7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

1

Class &Objectsin PHP: What is Class & Object, Creating and accessing a Class&Object,
Object properties, object methods, Overloading, inheritance, Constructor andDestructor
FormHandling:CreatingHTMLForm,HandlingHTMLFormdatainPHP
DatabaseHandlingUsingPHPwithMySQL:IntroductiontoMySQL:Databaseterms,DataTy
pes.

Php unit 4

Form Handling:
Creating HTML Form,:

Handling HTML Form data in PHP:


The PHP superglobals $_GET and $_POST are used to collect form-data.

We can create and use forms in PHP. To get form data, we need to use
PHP superglobals $_GET and $_POST.

The form request may be get or post. To retrieve data from get request,
we need to use $_GET, for post request $_POST.

PHP Get Form


Get request is the default form request. The data passed through get
request is visible on the URL browser so it is not secured. You can send
limited amount of data through get request.

Let's see a simple example to receive data from get request in PHP.

gg.html
<html>
<body>
<formaction="post1.php"method="get">
First Name: <inputtype="text"name="firstname"><br>
Last Name: <inputtype="text"name="lastname"><br>
<inputtype="submit"value="SUBMIT"><br>
</body>
</html>
Post1.php
<?php
$fname=$_GET['firstname'];
$lname=$_GET['lastname'];
echo"You first name is :".$fname."<br>";
echo"You last name is :".$lname;
?>
o/p:
2

Run as localhost/fazia/ gg.html to get output

PHP Post Form


Post request is widely used to submit form that have large amount of data
such as file upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so
it is secured. You can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

pp.html
<html>
<body>
<formaction="send1.php"method="post">
First Name: <inputtype="text"name="firstname"><br>
Last Name: <inputtype="text"name="lastname"><br>
<inputtype="submit"value="SUBMIT"><br>
</body>
</html>

Send1.php
<?php
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
echo"You first name is :".$fname."<br>";
echo"You last name is :".$lname;
?>

Run as localhost/fazia/pp.html to get output

Class &Objects in PHP:


What is Class & Object?
Define a Class
3

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:

What is an Object

If you look at the world around you, you’ll find many examples of tangible
objects: lamps, phones, computers, and cars. Also, you can find intangible
objects such as bank accounts and transactions.

All of these objects share the two common key characteristics:

 State
 Behavior

For example, a bank account has the state that consists of:

 Account number
 Balance

A bank account also has the following behaviors:

 Deposit
 Withdraw

PHP objects are conceptually similar to real-world objects because they consist
of state and behavior.

An object holds its state in variables that are often referred to as properties. An
object also exposes its behavior via functions which are known as methods.

What is a class?
4

In the real world, you can find many same kinds of objects. For example, a bank
has many bank accounts. All of them have account numbers and balances.

These bank accounts are created from the same blueprint. In object-oriented
terms, we say that an individual bank account is an instance of a Bank Account
class.

By definition, a class is the blueprint of objects. For example, from the Bank
Account class, you can create many bank account objects.

The following illustrates the relationship between the BankAccount class and its
objects. From the BankAccount class you can create
many BankAccount objects. And each object has its own account number and
balance.

Define a class

To define a class, you specify the class keyword followed by a name like this:
<?php

classClassName
{
//...
}Code language:HTML, XML(xml)
For example, the following defines a new class called BankAccount:
<?php

classBankAccount
{
}Code language:HTML, XML(xml)

By convention, you should follow these rules when defining a class:


5

 A class name should be in the upper camel case where each word is
capitalized. For example, BankAccount, Customer, Transaction,
and DebitNote.
 If a class name is a noun, it should be in the singular noun.
 Define each class in a separate PHP file.

From the BankAccount class, you can create a new bank account object by
using the new keyword like this:
<?php

classBankAccount
{
}

$account = new BankAccount();


Code language:HTML, XML(xml)
In this syntax, the $account is a variable that references the object created by
the Bank Account class. The parentheses that follow the BankAccount class
name are optional. Therefore, you can create a new BankAccount object like
this:
$account = new BankAccount;
Code language:PHP(php)

The process of creating a new object is also called instantiation. In other words,
you instantiate an object from a class. Or you create a new object from a class.

The BankAccount class is empty because it doesn’t have any state and behavior.

Add properties to a class

To add properties to the BankAccount class, you place variables inside it. For
example:
<?php

classBankAccount
{
public $accountNumber;
public $balance;
}Code language:HTML, XML(xml)
The BankAccount class has two properties $accountNumber and $balance. In
front of each property, you see the public keyword.
6

The public keyword determines the visibility of a property. In this case, you can
access the property from the outside of the class.
To access a property, you use the object operator (->) like this:
<?php

$object->property;
Code language:HTML, XML(xml)
The following example shows how to set the values of
the accountNumber and balance properties:
<?php

classBankAccount
{
public $accountNumber;
public $balance;
}

$account = new BankAccount();

$account->accountNumber = 1;
$account->balance = 100;
Code language:HTML, XML(xml)
Besides the public keyword, PHP also has private and protected keywords
which you’ll learn in the access modifiers tutorial.

Add methods to a class

The following shows the syntax for defining a method in a class:

<?php

classClassName
{
publicfunctionmethodName(parameter_list)
{
// implementation
}
}
Code language:HTML, XML(xml)
Like a property, a method also has one of the three visibility
modifiers: public, private, and protected. If you define a method without any
visibility modifier, it defaults to public.
The following example defines the deposit() method for the BankAccount class:
7

<?php

classBankAccount
{
public $accountNumber;

public $balance;

publicfunctiondeposit($amount)
{
if ($amount >0) {
$this->balance += $amount;
}
}
}
Code language:HTML, XML(xml)

The deposit() method accepts an argument $amount. It checks if the $amount is


greater than zero before adding it to the balance.
To call a method, you also use the object operator (->) as follows:
$object->method(arguments)Code language:PHP(php)
The new syntax in the deposit() method is the $this variable. The $this variable
is the current object of the BankAccount class.
For example, when you create a new object $account and call
the deposit() method, the $this inside the method is the $account object:
$account = new BankAccount();

$account->accountNumber = 1;
$account->balance = 100;

$account->deposit(100);
Code language:PHP(php)
Similarly, you can add the withdraw() method to the BankAccount class as
follows:
<?php

classBankAccount
{
public $accountNumber;

public $balance;

publicfunctiondeposit($amount)
8

{
if ($amount >0) {
$this->balance += $amount;
}
}

publicfunctionwithdraw($amount)
{
if ($amount <= $this->balance) {
$this->balance -= $amount;
returntrue;
}
returnfalse;

}
}
Code language:HTML, XML(xml)
The withdraw() method checks the current balance.
If the balance is less than the withdrawal amount, the withdraw() method
returns false.
Later, you’ll learn how to throw an exception instead. Otherwise, it deducts the
withdrawal amount from the balance and returns true.
PHP code to create class's object, access its
attributes
<?php

//PHP program to create an object of a class and access class attributes.

class Student

//Attributes

public $id;

public $name;

public $per;

}
9

$S = new Student();

$S->id = 101;

$S->name = "Rohit";

$S->per = 78.23;

print ("Student Id : " . $S->id . '<br>');

print ("Student Name: " . $S->name . '<br>');

print ("Student Percentage : " . $S->per . '<br>');


?>
o/p:
Student Id : 101
Student Name: Rohit
Student Percentage : 78.23

Summary

 Objects have states and behaviors.


 A class is a blueprint for creating objects.
 Properties represent the object’s state, and methods represent the object’s
behavior. Properties and methods have visibility.
 Use the new keyword to create an object from a class.
 The $this variable references the current object of the class.

Constructor and destructor in php:

<?php

// PHP program demonstrating a constructor and destructor in a class

class Student

// Attributes

public $id;

public $name;
10

public $per;

// Constructor to initialize properties

public function __construct($id, $name, $per)

$this->id = $id;

$this->name = $name;

$this->per = $per;

echo "Student object created.<br>";

// Method to display student details

public function display()

echo "Student Id : " . $this->id . "<br>";

echo "Student Name: " . $this->name . "<br>";

echo "Student Percentage : " . $this->per . "%<br>";

// Destructor to free resources

public function __destruct()

echo "Student object with ID " . $this->id . " is being


destroyed.<br>";

}
11

// Creating an object with values

$S = new Student(101, "Rohit", 78.23);

// Display student details

$S->display();

// Object will be destroyed automatically at the end of the script

?>

o/p:

Student object created.


Student Id : 101
Student Name: Rohit
Student Percentage : 78.23%
Student object with ID 101 is being destroyed.

What is $this in PHP?

In PHP, $this keyword references the current object of the class.


The $this keyword allows you to access the properties and methods of the
current object within the class using the object operator (->):
$this->property
$this->method()Code language:PHP(php)
The $this keyword is only available within a class. It doesn’t exist outside of the
class. If you attempt to use the $this outside of a class, you’ll get an error.

Introduction to PHP access modifiers

PHP has three access modifiers: public, private, and protected. In this tutorial,
you’ll focus on the public and private access modifiers.

 The public access modifier allows you to access properties and methods
from both inside and outside of the class.
12

 The private access modifier prevents you from accessing properties and
methods from the outside of the class.

The public access modifier

The following example illustrates the public access modifier:

<?php

class Customer
{
public $name;

public function getName()


{
return $this->name;
}
}
Code language: HTML, XML (xml)

In this example, the Customer class has a public property ($name)

and public method (getName()). And you can access the property and method
from both inside and outside of the class.

The private access modifier

To prevent access to properties and methods from outside of the class, you use
the private access modifier.
The following example changes $name property of the Customer class
from public to private:
<?php

classCustomer
{
private $name;

publicfunctiongetName()
{
return$this->name;
}
}Code language:HTML, XML(xml)
If you attempt to access the $name property from the outside of the class, you’ll
13

get an error. For example:


$customer = new Customer();
$customer->name = 'Bob';Code language:PHP(php)

Error:

Fatal error: Uncaught Error: Cannot access private property Customer::$name

Protected members :
A protected property or method is accessible in the class in which it is
declared, as well as in classes that extend that class. Protected members are
not available outside of those two kinds of classes. A class member can be
made protected by using protected keyword in front of the member

Creating and accessing a Class & Object:

Object properties:

object methods:

Overloading:
o Overloading in PHP provides means to dynamically create
properties and methods.
o These dynamic entities are processed via magic methods, one
can establish in a class for various action types.
o All overloading methods must be defined as Public.
o After creating object for a class, we can access set of entities that
are properties or methods not defined within the scope of the class.
o Such entities are said to be overloaded properties or methods,
and the process is called as overloading.
o For working with these overloaded properties or functions, PHP
magic methods are used.
o Most of the magic methods will be triggered in object context
except __callStatic () method which is used in static context.
14

PHP code to implement method overloading


based on the number of arguments
The source code to demonstrate the method overloading
based on the number of arguments is given below. The given
program is compiled and executed successfully.

<?php
//PHP program to demonstrate the method overloading
//based on the number of arguments.
class Sample
{
function __call($function_name, $args)
{

if ($function_name == 'sum')
{
switch (count($args))
{
case 2:
return $args[0] + $args[1];
case 3:
return $args[0] + $args[1] + $args[2];
}
}
}
}

$obj = new Sample();

printf("Sum: " . $obj->sum(10, 20) . "<br>");


printf("Sum: " . $obj->sum(10, 20, 30) . "<br>");
?>

Output
Sum: 30
Sum: 60

Explanation
15

Here, we created a class Sample and then implemented magic


function __call() to perform method overloading to add numbers
based on the number of arguments. Here, we used switch cases for
the number of arguments and return the sum of numbers.

At last, we created the object $obj of the Sample class and the
call sum method with a different number of arguments and print the
result on the webpage.

Property overloading
o PHP property overloading allows us to create dynamic properties in
object context.
o For creating those properties no separate line of code is needed.
o A property which is associated with class instance, and not declared
within the scope of the class, is considered as overloaded property.

Some of the magic methods which is useful for property


overloading.

o __set(): It is triggered while initializing overloaded properties.


o __get(): It is utilized for reading data from inaccessible Properties.
o __isset(): This magic method is invoked when we check overloaded
properties with isset() function.
o __unset(): This function will be invoked on using PHP unset() for
overloaded properties.

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.
16

Inheritance:

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 extends the features of a class by using 'extends'
keyword.

o It supports the concept of hierarchical classification.


o Inheritance has three types, single, multiple and multilevel
Inheritance.
o PHP supports only single inheritance, where only one class can
be derived from single parent class.
o We can simulate multiple inheritance by using interfaces.

o Inheritance in OOP = When a class derives from another class.


o 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.
o An inherited class is defined by using the extends keyword.

<?php
class a
{
function apple()
{
echo "An apple a day keeps the doctor away";
}
}
class b extends a
{
function mango ()
{
echo "One Rotten Mango can spoil the entire basket";
}
}
$obj= new b();
$obj->apple();
echo "<br>";
$obj= new b();
$obj->mango();
17

?>
o/p:
An apple a day keeps the doctor away
One Rotten Mango can spoil the entire basket

Constructor andDestructor:

PHP constructor is a special method that is called automatically when an object


is created.

PHP allows you to declare a constructor method for a class with the
name __construct() as follows:

<?php

class ClassName
{
function __construct()
{
// implementation
}
}

o/p:
good morning class
good morning class

PHP Destructor

 Use the __destruct() to define a destructor for a class.


 PHP automatically invokes the destructor when the object is deleted or
the script is terminated.
18

<?php
class constructordestructor
{
function __construct()
{
echo "object is initialized";
}

function __destruct()
{
echo "object is destroyed";
}
}
$obj=new constructordestructor();
?>
o/p:
object is initialized object is destroyed

example:
19

o/p:
caculate area of circlearea of circle=pi*r*robject is destroyed
FormHandling:
Creating HTML Form:
<html>
<body>
<form>
<label for="name">Name:</label>
<input type="text" name="name"><br><br>
<label for="sex">Sex:</label>
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
<input type="radio" name="sex" id="female" value="female">
<label for="female">Female</label><br><br>
<label for="country">Country: </label>
<select name="country" id="country">
<option>Select an option</option>
<option value="nepal">Nepal</option>
<option value="usa">USA</option>
<option value="australia">Australia</option>
</select><br><br>
<label for="message">Message:</label><br>
<textarea name="message" id="message" cols="30"
rows="4"></textarea><br><br>
<input type="checkbox" name="newsletter" id="newsletter">
<label for="newsletter">Subscribe?</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Handling HTML Form data in PHP:


DESCRIBE GET AND POST METHODS
20

Types of php constructors with example program:


A constructor is a special method in a class that is automatically called when an object is
created. In PHP, constructors are defined using the __construct() magic method. There are
three main types of constructors in PHP:

1. Default Constructor (No Parameters)


2. Parameterized Constructor
3. Copy Constructor (Manual Copying)

1. Default Constructor (No Parameters)

A default constructor is a constructor that does not take any arguments. It is automatically
called when an object is created.

Example: Default Constructor


<?php
class Student
{
// Default constructor
public function __construct()
{
echo "Default Constructor Called!<br>";
}
}

// Creating an object
$obj = new Student();
?>
Output:
Default Constructor Called!

2. Parameterized Constructor

A parameterized constructor accepts arguments to initialize object properties when the


object is created.

Example: Parameterized Constructor


<?php
class Student
{
public $name;
public $age;

// Parameterized Constructor
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}

public function display()


{
21

echo "Name: " . $this->name . "<br>";


echo "Age: " . $this->age . "<br>";
}
}

// Creating an object with parameters


$obj = new Student("John", 20);
$obj->display();
?>
Output:
Name: John
Age: 20

3. Copy Constructor (Manual Copying)

PHP does not support automatic copy constructors like C++. However, you can manually
copy one object's properties to another.

Example: Copy Constructor


<?php
class Student
{
public $name;
public $age;

// Parameterized Constructor
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}

// Copy Constructor (Manual Copying)


public function copyStudent(Student $obj)
{
$this->name = $obj->name;
$this->age = $obj->age;
}

public function display()


{
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age . "<br>";
}
}

// Creating an original object


$obj1 = new Student("Alice", 22);
$obj1->display();

// Creating a new object and copying values


$obj2 = new Student("", 0);
$obj2->copyStudent($obj1);
$obj2->display();
?>
Output:
makefile
22

CopyEdit
Name: Alice
Age: 22
Name: Alice
Age: 22

Summary:

Type of Constructor Description Example


No parameters, runs when object is
Default Constructor __construct()
created.
Parameterized Takes parameters to initialize __construct($name,
Constructor attributes. $age)
Manually copies data from one copyStudent(Student
Copy Constructor $obj)
object to another.

Introduction to MySQL:

What is MySQL?
 MySQL is a relational database management system
 MySQL is open-source
 MySQL is free
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, scalable, and easy to use
 MySQL is cross-platform
 MySQL is compliant with the ANSI SQL standard
 MySQL was first released in 1995
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

Who Uses MySQL?


 Huge websites like Facebook, Twitter, Airbnb, Booking.com, Uber,
GitHub, YouTube, etc.
 Content Management Systems like WordPress, Drupal, Joomla!, Contao,
etc.
 A very large number of web developers around the world

Database terms:
23

MySQL Database Terminology


One of the freely available, reliable and popular databases is MySQL and we will be
studying more about same in this series.
Before we proceed to explain the MySQL database system, let us have a look at few
definitions related to the database which are in general applicable to any other relational
databases as well.
1. Database - A database is a collection of tables, with related data.
2. Table - A table is a matrix with data. A table in a database looks like a simple
spreadsheet.
3. Column - One column (data element) contains data of one and the same kind,
for example, the column postcode.
4. Row - A row (= tuple, entry or record) is a group of related data, for example, the
data of one subscription.
5. Redundancy - Storing data twice in more than one tables, redundantly to make
the system faster.
6. Primary Key - A primary key is unique. A key value can not occur twice in one
table. With a key, you can only find one row. A table will have only one Primary
Key
7. Unique Key - A unique key is a combination of one or more columns which can
uniquely identify a row in the table. That combination cannot occur more than
once in one table excluding rows having NULL values in key columns. A table
can have more than one unique key.
8. Compound Key - A compound key (composite key) is a key that consists of
multiple columns because one column is not sufficiently unique. Another term for
the unique key which has more than one column.
9. Foreign Key - A foreign key is a linking pin between two tables.
10. Index - An index in a database resembles an index at the back of a book.
11. Referential Integrity - Referential Integrity makes sure that a foreign key value
always points to an existing row.

DataTypes.

Each column in a database table is required to have a name and a data type.

In MySQL there are three main data types: string, numeric, and date and
time.

String Data Types

Data type Description

CHAR(size) A FIXED length string (can contain letters, numbers, and special
24

characters). The size parameter specifies the column length in characters -


can be from 0 to 255. Default is 1

VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special
characters). The size parameter specifies the maximum column length in
characters - can be from 0 to 65535

BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter
specifies the column length in bytes. Default is 1

VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter
specifies the maximum column length in bytes.

TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT(size) Holds a string with a maximum length of 65,535 bytes

BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters

MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data

LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters


25

LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data

ENUM(val1, val2, A string object that can have only one value, chosen from a list of possible
val3, ...) values. You can list up to 65535 values in an ENUM list. If a value is
inserted that is not in the list, a blank value will be inserted. The values are
sorted in the order you enter them

SET(val1, val2, A string object that can have 0 or more values, chosen from a list of
val3, ...) possible values. You can list up to 64 values in a SET list

Numeric Data Types

Data type Description

BIT(size) A bit-value type. The number of bits per value is specified in size.
The size parameter can hold a value from 1 to 64. The default value
for size is 1.

TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is
from 0 to 255. The size parameter specifies the maximum display width
(which is 255)

BOOL Zero is considered as false, nonzero values are considered as true.


26

BOOLEAN Equal to BOOL

SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is
from 0 to 65535. The size parameter specifies the maximum display width
(which is 255)

MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned


range is from 0 to 16777215. The size parameter specifies the maximum
display width (which is 255)

INT(size) A medium integer. Signed range is from -2147483648 to 2147483647.


Unsigned range is from 0 to 4294967295. The size parameter specifies the
maximum display width (which is 255)

INTEGER(size) Equal to INT(size)

BIGINT(size) A large integer. Signed range is from -9223372036854775808 to


9223372036854775807. Unsigned range is from 0 to
18446744073709551615. The size parameter specifies the maximum
display width (which is 255)

FLOAT(size, d) A floating point number. The total number of digits is specified in size. The
number of digits after the decimal point is specified in the d parameter.
This syntax is deprecated in MySQL 8.0.17, and it will be removed in
future MySQL versions

FLOAT(p) A floating point number. MySQL uses the p value to determine whether
to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24,
the data type becomes FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE()
27

DOUBLE(size, d) A normal-size floating point number. The total number of digits is


specified in size. The number of digits after the decimal point is specified
in the d parameter

DOUBLE
PRECISION(size, d)

DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified


in size. The number of digits after the decimal point is specified in
the d parameter. The maximum number for size is 65. The maximum
number for d is 30. The default value for size is 10. The default value
for d is 0.

DEC(size, d) Equal to DECIMAL(size,d)

Note: All the numeric data types may have an extra option: UNSIGNED or
ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values
for the column. If you add the ZEROFILL option, MySQL automatically also
adds the UNSIGNED attribute to the column.

Date and Time Data Types

Data type Description

DATE A date. Format: YYYY-MM-DD. The supported range is


from '1000-01-01' to '9999-12-31'

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD


hh:mm:ss. The supported range is from '1000-01-01
00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT
and ON UPDATE in the column definition to get
automatic initialization and updating to the current
28

date and time

TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the


number of seconds since the Unix epoch ('1970-01-01
00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss. The
supported range is from '1970-01-01 00:00:01' UTC to
'2038-01-09 03:14:07' UTC. Automatic initialization and
updating to the current date and time can be specified
using DEFAULT CURRENT_TIMESTAMP and ON UPDATE
CURRENT_TIMESTAMP in the column definition

TIME(fsp) A time. Format: hh:mm:ss. The supported range is from


'-838:59:59' to '838:59:59'

YEAR A year in four-digit format. Values allowed in four-digit


format: 1901 to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.

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
 OOP makes it possible to create full reusable applications with less
code and shorter development time
29

PHP - What are Classes and Objects?


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

Look at the following illustration to see the difference between class and
objects:

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.

What is Class & Object:

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...
30

}
?>

Class:
A class is an entity that determines how an object will behave and what
the object will contain. In other words, it is a blueprint or a set of
instruction to build a specific type of object.

In PHP, declare a class using the class keyword, followed by the name of
the class and a set of curly braces ({}).

This is the blueprint of the construction work that is class, and the houses
and apartments made by this blueprint are the objects.

Syntax to Create Class in PHP

<?php
class MyClass
{
// Class properties and methods go here
}
?>

Important note:
In PHP, to see the contents of the class, use var_dump(). The var_dump()
function is used to display the structured information (type and value)
about one or more variables.

Syntax:
31

var_dump($obj);

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 MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>

Example of class and object:


<?php

class demo

private $a= "hello class";

public function display()

echo $this->a;

$obj = new demo();

$obj->display();

?>
32

o/p:

hello class

Use of var_dump($obj);
<?php

class demo

private $a= "The secret of life is enjoying the passage of time";

public function display()

echo $this->a;

$obj = new demo();

var_dump($obj);

?>

Output:

object(demo)#1 (1) { ["a":"demo":private]=> string(50) "The secret of life is


enjoying the passage of time" }

Overloading:

o Overloading in PHP provides means to dynamically create


properties and methods.
o These dynamic entities are processed via magic methods, one
can establish in a class for various action types.
o All overloading methods must be defined as Public.
33

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

Property overloading
o PHP property overloading allows us to create dynamic properties in
object context.
o For creating those properties no separate line of code is needed.
o A property which is associated with class instance, and not declared
within the scope of the class, is considered as overloaded property.

Some of the magic methods which is useful for property


overloading.

o __set(): It is triggered while initializing overloaded properties.


o __get(): It is utilized for reading data from inaccessible Properties.
o __isset(): This magic method is invoked when we check overloaded
properties with isset() function.
o __unset(): This function will be invoked on using PHP unset() for
overloaded properties.

Inheritance:
34

Inheritance
Inheritance is very useful if we want to create several
similar classes. We can put the common properties
and methods in one parent class and then inherit it
in the child classes. Syntax for Inheriting a Class

In PHP, extends keyword is used to specify the name of


the parent class while defining the child class. For
example,

<?php

classHuman {

// parent class code

classMaleextendsHuman {

// child class code

classFemaleextendsHuman {

// child class code

?>

Copy
35

Some important points to remember while using


inheritance are:

1. Child class can access and use only the non-


private properties and methods on the parent class.
2. Child class can have it's own methods too, which will
not be available to the parent class.
3. Child class can also override a method defined in the
parent class and provide its own implementation for it.
The class which is inherited is
called Parent class(or super class or base class) while the
class which is inheriting other class is called
as Child class(or sub class or derived class).

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 extends the features of a class by using 'extends'
keyword.

o It supports the concept of hierarchical classification.


o Inheritance has three types, single, multiple , hierarchical and
multilevel Inheritance.
o PHP supports only single inheritance, where only one class can
be derived from single parent class.
o We can simulate multiple inheritance by using interfaces.

<?php
class a
{
function fun1()
{
echo "hi php";
}
}
class b extends a
{
function fun2()
{
36

echo "welcome";
}
}
$obj= new b();
$obj->fun1();
?>
o/p: hi php

1. Single Inheritance
class Animal:
def speak(self):
print("Animal speaks")

# Child class
class Dog(Animal):
def bark(self):
print("Dog barks")

# Object of Dog
dog = Dog()
dog.speak() # Inherited method
dog.bark()

output:
Animal speaks
Dog barks

2. Multiple Inheritance
class Father:
def skills(self):
print("Father: Gardening, Programming")

# Parent class 2
class Mother:
def skills(self):
print("Mother: Cooking, Art")

# Child class
class Child(Father, Mother):
def skills(self):
super().skills() # Calls Father's skills (due to method resolution
order)
print("Child: Python, Gaming")

# Object of Child
37

c = Child()
c.skills()

output:
Father: Gardening, Programming
Child: Python, Gaming

3. Multilevel Inheritance
class Grandparent:
def house(self):
print("Grandparent: Owns a house")

# Derived class
class Parent(Grandparent):
def car(self):
print("Parent: Owns a car")

# Further Derived class


class Child(Parent):
def bike(self):
print("Child: Owns a bike")

# Object of Child
c = Child()
c.house() # From Grandparent
c.car() # From Parent
c.bike() # Own method

output:
Grandparent: Owns a house
Parent: Owns a car
Child: Owns a bike

4.Hierarchical Inheritance

class Animal:
def speak(self):
print("Animal makes a sound")

# Child class 1
class Dog(Animal):
def bark(self):
print("Dog barks")

# Child class 2
class Cat(Animal):
def meow(self):
print("Cat meows")
38

# Creating objects
dog = Dog()
cat = Cat()

# Calling methods
dog.speak() # Inherited from Animal
dog.bark() # Dog's own method

cat.speak() # Inherited from Animal


cat.meow() # Cat's own method

output:
Animal makes a sound
Dog barks
Animal makes a sound
Cat meows

Accessing Class Variables and Methods

To access class variable and methods using the object of


the class, we use the -> operator followed by the name of
the variable or the method's name.

We have already showcased this in the example above, but


let's have another example, with a little more complex
class.

<?php

class Person {

// first name of person

var $fname;

// last name of person

var $lname;

function showName() {

echo "My name is: " . $this->fname . " " . $this->lname;


39

// creating class object

$john = new Person();

// assigning values to variables

$john->fname = "John";

$john->lname = "Wick";

// calling the method function

$john->showName();

?>

o/p:

My name is: John Wick

PHP Access Modifiers


To set the access rights for class methods and variables we
use access modifiers which are nothing but PHP keywords.
We can even assign some of these access modifiers to the
class itself to make the class behave in a special way.

Following are the PHP keywords which are used as access


modifiers along with their meaning:

1. public: When we define class members as public, then


they are accessible from anywhere, even from outside
of the class scope.
2. private: When we define class members as private,
they can only be accessed from within the class itself.
40

3. protected: This is same as private, with one exception,


the class members defined as protected can still be
accessed from its subclass(We will learn about
subclasses when we will learn about Inheritance).
4. abstract: This keyword is only used for PHP classes and
its member functions.
5. final: The class methods defined as final, can not be
changed or overriden by any subclass.

When to use Which Access Modifier

We cannot use all the available access modifers with class,


its varibales and methods. In the table below, we have
specified which access specifier is applied to what:

Access functio
classes variables
Modifer ns

Not Applicabl
public Applicable
Applicable e

Not Applicabl
private Applicable
Applicable e

Not Applicabl
protected Applicable
Applicable e

Applicabl Not
abstract Applicable
e Applicable
41

Applicabl Not
final Applicable
e Applicable

Difference between abstract Class and Interface

Following are a few important differences between an


abstract class and an interface:

Interface Abstract Class

An interface cannot
have concrete An abstract class can have
methods in it i.e. both abstract methods and concrete
methods with methods in it.
definition.

All methods declared An abstract class can


in interface should have public, private and protected etc
be public methods.

Multiple interfaces can


One class can extend only one
be implemented by
abstract class.
one class.

https://www.youtube.com/watch?v=eJeBn3miOoE

You might also like