Php unit 4 nep[1]
Php unit 4 nep[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,:
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.
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
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;
?>
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.
State
Behavior
For example, a bank account has the state that consists of:
Account number
Balance
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)
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
{
}
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.
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->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.
<?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)
$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
class Student
//Attributes
public $id;
public $name;
public $per;
}
9
$S = new Student();
$S->id = 101;
$S->name = "Rohit";
$S->per = 78.23;
Summary
<?php
class Student
// Attributes
public $id;
public $name;
10
public $per;
$this->id = $id;
$this->name = $name;
$this->per = $per;
}
11
$S->display();
?>
o/p:
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.
<?php
class Customer
{
public $name;
and public method (getName()). And you can access the property and method
from both inside and outside of the class.
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
Error:
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
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
//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];
}
}
}
}
Output
Sum: 30
Sum: 60
Explanation
15
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.
Inheritance:
<?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 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
<?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>
A default constructor is a constructor that does not take any arguments. It is automatically
called when an object is created.
// Creating an object
$obj = new Student();
?>
Output:
Default Constructor Called!
2. Parameterized Constructor
// Parameterized Constructor
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
PHP does not support automatic copy constructors like C++. However, you can manually
copy one object's properties to another.
// Parameterized Constructor
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
CopyEdit
Name: Alice
Age: 22
Name: Alice
Age: 22
Summary:
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
Database terms:
23
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.
CHAR(size) A FIXED length string (can contain letters, numbers, and special
24
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
BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
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
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)
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)
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
PRECISION(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.
Look at the following illustration to see the difference between class and
objects:
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
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.
<?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.
Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
class demo
echo $this->a;
$obj->display();
?>
32
o/p:
hello class
Use of var_dump($obj);
<?php
class demo
echo $this->a;
var_dump($obj);
?>
Output:
Overloading:
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.
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
<?php
classHuman {
classMaleextendsHuman {
classFemaleextendsHuman {
?>
Copy
35
<?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")
# 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
output:
Animal makes a sound
Dog barks
Animal makes a sound
Cat meows
<?php
class Person {
var $fname;
var $lname;
function showName() {
$john->fname = "John";
$john->lname = "Wick";
$john->showName();
?>
o/p:
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
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.
https://www.youtube.com/watch?v=eJeBn3miOoE