DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
unit 1 :
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING IN PHP
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
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
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
} ?>
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:
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
}
function get_name() {
return $this->name;
}
}
?>
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, but they will have different property values.
Objects of a class is created using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
// 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');
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$banana->set_name('Banana');
echo $apple->get_name(); echo "
"; echo $banana->get_name();
?>
In the example below, we add two more methods to class Fruit, for setting and getting the $color property:
// Properties
public $name;
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$apple->set_color('Red'); echo "Name: " . $apple->get_name(); echo "
"; echo "Color: " . $apple->get_color();
?>
PHP - The $this Keyword
The $this keyword refers to the current object, and is only available inside methods.
Look at the following example:
So, where can we change the value of the $name property? There are two ways:
1. Inside the class (by adding a set_name() method and use $this):
2. Outside the class (by directly changing the property value):
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:
// Properties
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit(); var_dump($apple instanceof Fruit);
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP OOP - Constructor
PHP - The __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.
Notice that the construct function starts with two underscores (__)!
We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code:
public $name;
public $color;
function __construct($name) {
$this->name = $name;
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple"); echo $apple->get_name();
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red"); echo $apple->get_name(); echo "
"; echo $apple->get_color();
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
?>
PHP - The __destruct Function
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.
Notice that the destruct function starts with two underscores (__)!
The example below has a __construct() function that is automatically called when you create an object from a class, and a __destruct() function that is automatically called at the end of the script:
public $name;
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
// Properties
var $name;
var $color;
// Methods
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
$apple = new Fruit("Apple", "red");
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - Access Modifiers
Properties and methods can have access modifiers which control where they can be accessed.
There are three access modifiers:
public - the property or method can be accessed from everywhere. This is default protected - the property or method can be accessed within the class and by classes derived from that class private - the property or method can ONLY be accessed within the class
In the following example we have added three different access modifiers to the three properties. Here, if you try to set the name property it will work fine (because the name property is public). However, if you try to set the color or weight property it will result in a fatal error (because the color and weight property are protected and private):
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>
In the next example we have added access modifiers to two methods. Here, if you try to call the set_color() or the set_weight() function it will result in a fatal error (because the two functions are considered protected and private), even if all the properties are public:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
public $color;
public $weight;
function set_name($n) { // a public function (default)
$this->name = $n;
}
protected function set_color($n) { // a protected function
$this->color = $n;
}
private function set_weight($n) { // a private function
$this->weight = $n;
}
}
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>
PHP - What is Inheritance?
Inheritance in OOP = When a class derives from another class.
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.
An inherited class is defined by using the extends keyword.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
PHP - Inheritance and the Protected Access Modifier
In the previous chapter we learned that protected properties or methods can be accessed within the class and by classes derived from that class. What does that mean?
Let's look at an example:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
// Try to call all three methods from outside class
$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>
In the example above we see that if we try to call a protected method (intro()) from outside the class, we will receive an error. public methods will work fine!
Let's look at another example:
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
// Call protected function from within derived class - OK
$this -> intro();
}
}
$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public
$strawberry->message(); // OK. message() is public and it calls intro() (which is protected) from within the derived class
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - Overriding Inherited Methods
Inherited methods can be overridden by redefining the methods (use the same name) in the child class.
Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will override the __construct() and intro() methods in the parent class (Fruit):
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public $weight;
public function __construct($name, $color, $weight) {
$this->name = $name;
$this->color = $color;
$this->weight = $weight;
}
public function intro() {
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight} gram.";
}
}
$strawberry = new Strawberry("Strawberry", "red", 50);
$strawberry->intro();
?>
PHP - The final Keyword
The final keyword can be used to prevent class inheritance or to prevent method overriding.
The following example shows how to prevent class inheritance:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
}
class Strawberry extends Fruit {
}
?>
The following example shows how to prevent method overriding:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
class Fruit {
final public function intro() {
}
}
class Strawberry extends Fruit {
// will result in error
public function intro() {
}
}
?>
PHP - Class Constants
Constants cannot be changed once it is declared.
Class constants can be useful if you need to define some constant data within a class.
A class constant is declared inside a class with the const keyword.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
We can access a constant from outside the class by using the class name followed by the scope resolution operator (::) followed by the constant name, like here:
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo Goodbye::LEAVING_MESSAGE;
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}
$goodbye = new Goodbye();
$goodbye->byebye();
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - What are Abstract Classes and Methods?
Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks.
An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code.
An abstract class or method is defined with the abstract keyword:
Syntax
When inheriting from an abstract class, the child class method must be defined with the same name, and the same or a less restricted access modifier. So, if the abstract method is defined as protected, the child class method must be defined as either protected or public, but not private. Also, the type and number of required arguments must be the same. However, the child classes may have optional arguments in addition.
So, when a child class is inherited from an abstract class, we have the following rules:
The child class method must be defined with the same name and it redeclares the parent abstract method The child class method must be defined with the same or a less restricted access modifier
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
The number of required arguments must be the same. However, the child class may have optional arguments in addition
Let's look at an example:
// Parent class abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}
// Child classes class Audi extends Car {
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}
class Volvo extends Car {
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}
class Citroen extends Car {
public function intro() : string {
return "French extravagance! I'm a $this->name!";
}
}
// Create objects from the child classes
$audi = new audi("Audi");
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
echo $audi->intro(); echo "
";
$volvo = new volvo("Volvo"); echo $volvo->intro(); echo "
";
$citroen = new citroen("Citroen"); echo $citroen->intro();
?>
Example Explained
The Audi, Volvo, and Citroen classes are inherited from the Car class. This means that the Audi, Volvo, and Citroen classes can use the public $name property as well as the public __construct() method from the Car class because of inheritance.
But, intro() is an abstract method that should be defined in all the child classes and they should return a string.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - What are Interfaces?
Interfaces allow you to specify what methods a class should implement.
Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".
Interfaces are declared with the interface keyword:
Syntax
PHP - Interfaces vs. Abstract Classes
Interface are similar to abstract classes. The difference between interfaces and abstract classes are:
Interfaces cannot have properties, while abstract classes can All interface methods must be public, while abstract class methods is public or protected All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary Classes can implement an interface while inheriting from another class at the same time
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - Using Interface implements keyword is used in interface .
To implement an interface, a class must use the implements keyword.
A class that implements an interface must implement all of the interface's methods.
public function makeSound();
}
class Cat implements Animal {
public function makeSound() {
echo "Meow";
}
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
}
$animal = new Cat();
$animal->makeSound();
?>
From the example above, let's say that we would like to write software which manages a group of animals. There are actions that all of the animals can do, but each animal does it in its own way.
Using interfaces, we can write some code which can work for all of the animals even if each animal behaves differently:
// Interface definition
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
interface Animal {
public function makeSound();
}
// Class definitions class Cat implements Animal {
public function makeSound() {
echo " Meow ";
}
}
class Dog implements Animal {
public function makeSound() {
echo " Bark ";
}
}
class Mouse implements Animal {
public function makeSound() {
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
echo " Squeak ";
}
}
// Create a list of animals
$cat = new Cat();
$dog = new Dog();
$mouse = new Mouse();
$animals = array($cat, $dog, $mouse);
// Tell the animals to make a sound foreach($animals as $animal) {
$animal->makeSound();
}
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - What are Traits?
PHP only supports single inheritance: a child class can inherit only from one single parent.
So, what if a class needs to inherit multiple behaviors? OOP traits is used to solve this problem.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
Traits are declared with the trait keyword:
Syntax
To use a trait in a class, use the use keyword:
Syntax
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Let's look at an example:
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$obj->msg1();
?>
PHP - Static Methods
Static methods can be called directly - without creating an instance of the class first.
Static methods are declared with the static keyword:
Syntax
To access a static method use the class name, double colon (::), and the method name:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public static function welcome() {
echo "Hello World!";
}
}
// Call static method greeting::welcome();
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - More on Static Methods
A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::):
public static function welcome() {
echo "Hello World!";
}
public function __construct() {
self::welcome();
}
}
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
new greeting();
?>
PHP - Static Properties
Static properties can be called directly - without creating an instance of a class.
Static properties are declared with the static keyword:
Syntax
To access a static property use the class name, double colon (::), and the property name:
Syntax
ClassName::staticProp;
Let's look at an example:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public static $value = 3.14159;
}
// Get static property echo pi::$value;
?>
PHP - More on Static Properties
A class can have both static and non-static properties. A static property can be accessed from a method in the same class using the self keyword and double colon (::):
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
public static $value=3.14159;
public function staticValue() {
return self::$value;
}
}
// Get static property
$pi = new pi(); echo $pi->staticValue();
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - What is an Iterable?
An iterable is any value which can be looped through with a foreach() loop.
The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.
PHP - Using Iterables
The iterable keyword can be used as a data type of a function argument or as the return type of a function:
foreach($myIterable as $item) {
echo $item;
}
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
}
$arr = ["a", "b", "c"]; printIterable($arr);
?>
PHP Namespaces
Namespaces are qualifiers that solve two different problems:
1. They allow for better organization by grouping classes that work together to perform a task 2. They allow the same name to be used for more than one class
For example, you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.
Declaring a Namespace
Namespaces are declared at the beginning of a file using the namespace keyword:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Syntax
Declare a namespace called Html: namespace Html;
public $title = "";
public $numRows = 0;
public function message() {
echo "
Table '{$this->title}' has {$this->numRows} rows.
";}
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$table->message();
?>
UNIT 2- WEB-TECHNIQUES
$_SERVER is a superglobal that holds information regarding HTTP headers, path and script location etc. All the server and execution environment related information is available in this associative array. Most of the entries in this array are populated by web server. PHP versions prior to 5.4.0 contained $HTTP_SERVER_VARS contained same information but has now been removed. Following are some prominent members of this array PHP_SELF − stores filename of currently executing script. For example, a script in test folder of document root of a local server returns its path as follows − Example
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
echo $_SERVER['PHP_SELF'];
?>
This results in following output in browser with http://localhost/test/testscript.php URL
/test/testscript.php SERVER_ADDR − This property of array returns The IP address of the server under which the current script is executing. SERVER_NAME − Name of server hostunder which the current script is executing.In case of a ever running locally, localhost is returned QUERY_STRING − A query string is the string of key=value pairs separated by & symbol and appended to URL after ? symbol. For example, http://localhost/testscript?name=xyz&age=20 URL returns trailing query string REQUEST_METHOD − HTTP request method used for accessing a URL, such as POST, GET, POST, PUT or DELETE. In above query string example, a URL attached to query string wirh ? symbol requests the page with GET method DOCUMENT_ROOT − returns name of directory on server that is configured as document root. On XAMPP apache server it returns htdocs as name of document root
C:/xampp/htdocs DOCUMENT_ROOT − This is a string denoting the user agent (browser) being which is accessing the page.
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 REMOTE_ADDR − IP address of machine from which the user is viewing the current page. SERVER_PORT − port number on which the web server is listening to incoming request. Default is 80
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Following script invoked from document root of XAMPP server lists all server variables Example
$v) echo $k . "=>" . $v . "
";
?>
List of all server variables
MIBDIRS=>C:/xampp/php/extras/mibs MYSQL_HOME=>\xampp\mysql\bin OPENSSL_CONF=>C:/xampp/apache/bin/openssl.cnf PHP_PEAR_SYSCONF_DIR=>\xampp\php PHPRC=>\xampp\php TMP=>\xampp\tmp HTTP_HOST=>localhost HTTP_CONNECTION=>keep-alive HTTP_CACHE_CONTROL=>max-age=0 HTTP_DNT=>1 HTTP_UPGRADE_INSECURE_REQUESTS=>1 HTTP_USER_AGENT=>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 HTTP_ACCEPT=>text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apn g,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 HTTP_SEC_FETCH_SITE=>none HTTP_SEC_FETCH_MODE=>navigate HTTP_SEC_FETCH_USER=>?1 HTTP_SEC_FETCH_DEST=>document HTTP_ACCEPT_ENCODING=>gzip, deflate, br
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
HTTP_ACCEPT_LANGUAGE=>en-US,en;q=0.9,mr;q=0.8 PATH=>C:\python37\Scripts\;C:\python37\;C:\Windows\system32;C:\Windows;C:\Windows\Sys tem32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenS SH\;C:\Program Files (x86)\AMD\ATI.ACE\Core- Static;C:\python37\Scripts\;C:\python37\;C:\Users\User\AppData\Local\Microsoft\WindowsAp ps;C:\Users\User\AppData\Local\Programs\MiKTeX 2.9\miktex\bin\x64\;C:\MicrosoftVSCode\bin SystemRoot=>C:\Windows COMSPEC=>C:\Windows\system32\cmd.exe PATHEXT=>.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW WINDIR=>C:\Windows SERVER_SIGNATURE=> Apache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32 Server at localhost Port 80
SERVER_SOFTWARE=>Apache/2.4.41 (Win64) OpenSSL/1.0.2s PHP/7.1.32 SERVER_NAME=>localhost SERVER_ADDR=>::1 SERVER_PORT=>80 REMOTE_ADDR=>::1 DOCUMENT_ROOT=>C:/xampp/htdocs REQUEST_SCHEME=>http CONTEXT_PREFIX=> CONTEXT_DOCUMENT_ROOT=>C:/xampp/htdocs SERVER_ADMIN=>postmaster@localhost SCRIPT_FILENAME=>C:/xampp/htdocs/testscript.php REMOTE_PORT=>49475 GATEWAY_INTERFACE=>CGI/1.1 SERVER_PROTOCOL=>HTTP/1.1 REQUEST_METHOD=>GET QUERY_STRING=> REQUEST_URI=>/testscript.php SCRIPT_NAME=>/testscript.php
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP_SELF=>/testscript.php REQUEST_TIME_FLOAT=>1599118525.327 REQUEST_TIME=>1599118525
PHP Complete Form Example
PHP - Keep The Values in The Form
To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the tags. The little script outputs the value of the $name, $email, $website, and $comment variables.
Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } }
if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } }
if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0- 9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } }
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); }
if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
PHP Form Validation Example
* required field
Your Input:"; echo $name; echo "
"; echo $email; echo "
"; echo $website; echo "
"; echo $comment; echo "
"; echo $gender; ?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
here are two ways the browser client can send information to the web server.
The GET Method The POST Method Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand. name1=value1&name2=value2&name3=value3 Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
The GET Method
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server logs, in the browser's Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to the server.
GET can't be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment variable.
The PHP provides $_GET associative array to access all the sent information using GET method.
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get".
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.
The example below shows the code in "test_get.php":
Try out following example by putting the source code in test.php script. "; echo "You are ". $_GET['age']. " years old.";
exit(); } ?>
It will produce the following result −
The POST Method
The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides $_POST associative array to access all the sent information using POST method.
PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.
The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Advantages of GET
Here, are benefits/ pros of using GET:
The GET method can retrieve information identified by the request-URl (Uniform Resource Identifier). GET requests can be viewed in the browser history.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
It enables you to save the results of a HTML form. You can easily use GET method to request required data.
Advantages of POST
Here, are benefits/ pros of using POST:
This method helps you to determine resource URI. Specifying a new resource location header is very easy using location header. You can send a request to accept the entity as a new resource, which is identified by the URI. You can send user-generated data to the web server. It is very useful when you do not have any idea about the resource you have to keep in the URL. Use POST when you need the server, which controls URL generation of your resources. POST is a secure method as its requests do not remain in browser history. You can effortlessly transmit a large amount of data using post. You can keep the data private. This method can be used to send binary as well as ASCII data.
Disadvantages of GET
Here, are cons/drawback of using GET:
GET can't be used to send word documents or images. GET requests can be used only to retrieve data The GET method cannot be used for passing sensitive information like usernames and passwords. The length of the URL is limited. If you use GET method, the browser appends the data to the URL. You can easily bookmark Query string value in GET
Disadvantages of POST
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Here, are cons/drawback of using POST:
It is not possible to save data as the data sent by the POST method is not visible in the URL. You cannot see POST requests in browser history. This method is not compatible with many firewall setups. You cannot use spaces, tabs, carnage returns, etc. This method is not compatible with some firewall setups. POST method takes lots of time when uploading the large binary file.
KEY DIFFERENCE:
In GET method, values are visible in the URL while in POST method, values are NOT visible in the URL. GET has a limitation on the length of the values, generally 255 characters whereas POST has no limitation on the length of the values since they are submitted via the body of HTTP. GET method supports only string data types while POST method supports different data types, such as string, numeric, binary, etc. GET request is often cacheable while POST request is hardly cacheable. GET performs are better compared to POST.
The difference between GET and POST Method.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP Forms Required Inputs
❮ PreviousNext ❯
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
So far, any input in our form was optional. But, when we create forms, we need to have required input fields. As an example, email field should not empty, otherwise it should show an error.
In PHP, we use empty() function to check whether an input is empty or not. This function returns true on following cases.
"" - In an empty string 0 - 0 as an integer 0.0 - 0 as a float
"0" - 0 as string null false [] - empty array
In the following example, form and handler will be on the same script. Then, we will show error messages inside the forms.
Tip: Data of non-form element (
Required Input Fields
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // request method is post // now handle the form data
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
// declare name and email variables $name = $email = '';
if (empty($_POST['name'])) { $nameError = 'Name should be filled'; } else { $name = trim(htmlspecialchars($_POST['name'])); }
if (empty($_POST['email'])) { $emailError = 'Please add your email'; } else { $email = trim(htmlspecialchars($_POST['name'])); }
} ?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP Forms Sticky
Sticky inputs are auto-filling inputs after submitting
In previous examples, if user forgot to fill the email, an error message was shown. Also, all other inputs were cleared. Sticky inputs prevents this annoying mistake.
To do this, the form and handler should be on the same script. It is pretty easy to make our form sticky. We need to echo the submitted name and email as the value attribute of the input fields.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Sticky Input Fields
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $email = '';
if (empty($_POST['name'])) { $nameError = 'Name should be filled'; } else { $name = trim(htmlspecialchars($_POST['name'])); }
if (empty($_POST['email'])) { $emailError = 'Please add your email'; } else { $email = trim(htmlspecialchars($_POST['name'])); }
} ?>
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Unit 3 :- XML
a. XML stands for eXtensibleMarkup Language b. XML is a markup language much like HTML c. XML was designed to store and transport data d. XML was designed to be self-descriptive
XML Does Not DO Anything:
Maybe it is a little hard to understand, but XML does not DO anything.
This note is a note to Tove from Jani, stored as XML:
XML Example 1
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
The XML above is quite self-descriptive:
. It has sender information. . It has receiver information . It has a heading . It has a message body.
But still, the XML above does not DO anything. XML is just information wrapped in tags.
Someone must write a piece of software to send, receive, store, or display it:
Note
To: Tove From:
Jani
Reminder
Don't forget me this weekend!
Why Study XML?
XML plays an important role in many different IT systems.
XML is often used for distributing data over the Internet.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
It is important (for all types of software developers!) to have a good understanding of XML.
XML Does Not Use Predefined Tags:
The XML language has no predefined tags.
The tags in the example above (like
HTML works with predefined tags like
,
,
Name | "; $display_string .= "Age | "; $display_string .= "Sex | ";WPM | "; $display_string .= "
---|---|---|---|
$row[name] | "; $display_string .= "$row[age] | "; $display_string .= "$row[sex] | "; $display_string .= "$row[wpm] | "; $display_string .= "
?>
Now try by entering a valid value in "Max Age" or any other box and then click Query MySQL button.
Top of Form
Max Age:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Max WPM:
Sex:
Bottom of Form
Your result will display here
If you have successfully completed this lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.
======//======//======
PHP & XML
XML is a markup language that looks a lot like HTML. An XML document is plain text and contains tags delimited by < and >.There are two big differences between XML and HTML −
XML doesn't define a specific set of tags you must use. XML is extremely picky about document structure.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
XML gives you a lot more freedom than HTML. HTML has a certain set of tags: the tags surround a link, the
starts paragraph and so on. An XML document, however, can use any tags you want. Put
XML is very strict when it comes to document structure. HTML lets you play fast and loose with some opening and closing tags. But this is not the case with XML.
- Braised Sea Cucumber
- Baked Giblets with Salt HTML list
- Abalone that's not validwith Marrow XML and Duck Feet
This is not a valid XML document because there are no closing
HTML list that is valid XML
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
- Braised Sea Cucumber
- Baked Giblets with Salt
- Abalone with Marrow and Duck Feet
Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages.
Ajax refers to JavaScript and XML, technologies that are widely used for creating dynamic and asynchronous web content. While Ajax is not limited to JavaScript and XML technologies, more often than not they are used together by web applications. The focus of this tutorial is on using JavaScript based Ajax functionality in JavaServer Faces web applications. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Ajax and forms:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
jQuery's ajax capabilities can be especially useful when dealing with forms. There are several advantages, which can range from serialization, to simple client-side validation
1) Serialization: Serializing form inputs in jQuery is extremely easy. Two methods come supported natively: .serialize() and .serializeArray(). While the names are fairly self-explanatory, there are many advantages to using them.
The .serialize() method serializes a form's data into a query string. For the element's value to be serialized, it must have a name attribute. Please note that values from inputs with a type of checkbox or radio are included only if they are checked. // Turning form data into a query string. $( "#myForm" ).serialize(); Creates a query string like this: field_1=something&field2=somethingElse
While plain old serialization is great, sometimes your application would work better if you sent over an array of objects, instead of just the query string. For that, jQuery has the .serializeArray() method. It's very similar to the .serialize() method listed above, except it produces an array of objects, instead of a string.
/ Creating an array of objects containing form data
$( "#myForm" ).serializeArray(); Creates a structure like this:
[ { name : "field_1", value : "something"
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
}, { name : "field_2", value : "somethingElse"}
2) Client-side validation: Client-side validation is, much like many other things, extremely easy using jQuery. While there are several cases developers can test for, some of the most common ones are: presence of a required input, valid usernames/emails/phone numbers/etc…, or checking an "I agree…" box.
Please note that it is advisable that you also perform server-side validation for your inputs. However, it typically makes for a better user experience to be able to validate some things without submitting the form.
Ajax events:
Ajax requests produce a number of different events that you can subscribe to. Here's a full list of the events and in what order they are triggered.
There are two types of events:
1) Local events: These are callbacks that you can subscribe to within the Ajax request object, like so:
$.ajax({ beforeSend: function(){
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
// Handle the beforeSend event
}, complete: function(){
// Handle the complete event
}
2) Global Events: These events are triggered on the document, calling any handlers which may be listening. You can listen for these events like so:
$(document).bind("ajaxSend", function(){
$("#loading").show();
}).bind("ajaxComplete", function(){
$("#loading").hide();
});
Global events can be disabled for a particular Ajax request by passing in the global option, like so:
$.ajax({ url: "test.html", global: false,});
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Ajax -Events:
This is the full list of Ajax events, and in the order in which they are triggered. The indented events are triggered for each and every Ajax request (unless a global option has been set). The ajaxStart and ajaxStop events are events that relate to all Ajax requests together.
1) ajaxStart (Global Event): This event is triggered if an Ajax request is started and no other Ajax requests are currently running.
2) beforeSend (Local Event): This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
3) ajaxSend (Global Event): This global event is also triggered before the request is run.
4) success (Local Event): This event is only called if the request was successful (no errors from the server, no errors with the data):
5) ajaxSuccess (Global Event): This event is also only called if the request was successful.
6) error (Local Event): This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
7) ajaxError (Global Event): This global event behaves the same as the local error event.
8) complete (Local Event):
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
9) ajaxComplete (Global Event): This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
10) ajaxStop (Global Event): This global event is triggered if there are no more Ajax requests being processed.
JQuery’s AJAX related methods:
The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.
Syntax: $.ajax({name:value, name:value, ... })
The parameters specifies one or more name/value pairs for the AJAX request. Async:
Set to false if the request should be sent synchronously. Defaults to true. Note that if you set this option to false, your request will block execution of other code until the response is received. link cache:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Whether to use a cached response if available. Defaults to true for all dataTypes except "script" and "jsonp". When set to false, the URL will simply have a cachebusting parameter appended to it. done:
A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the dataType was JSON), as well as the text status of the request and the raw request object. fail:
A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request. always:
A callback function to run when the request is complete, regardless of success or failure. The function receives the raw request object and the text status of the request. context:
The scope in which the callback function(s) should run (i.e. what this will mean inside the callback function(s)). By default, this inside the callback function(s) refers to the object originally passed to $.ajax().
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Unit 5
introduction to Web services
Introduction: -
A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. Web services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or web-based.
Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML. Here are the advantages of utilizing web services are: 1. Revealing the Existing Function on Framework. 2. Interoperability 3. Ordered Protocol
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
4. Ease of Use 5. Re-Ease of Use 6. Send Capacity 7. Agility 8. Qualit 9. Cost 10. Minimal Effort Communication(XML-Based)
Disadvantages and Pitfalls of Web Services
1. Pitfalls of Web Services. 2. Performance Issues. 3. Lack of Standards. 4. Newness of Web Service Technology. 5. Staffing Issues. 6. Q&. 7. Workshop. Components of Web Services: -
The basic web services platform is XML + HTTP. All the standard web services work using the following components −
1. SOAP (Simple Object Access Protocol) 2. UDDI (Universal Description, Discovery and Integration) 3. WSDL (Web Services Description Language)
Web Services - Characteristics
Web services have the following characteristics:
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
1. XML-based 2. Coarse-grained 3. Loosely coupled 4. Capability to be synchronous and asynchronous 5. Supports RPC
2. XML-based
Web services use XML at data representation and data transportation layers. Using XML eliminates any networking, operating system, or platform binding. Web services-based applications are highly interoperable at their core level.
3. Cross-gained
In the coarse-grained operation, a few objects hold a lot of related data. It provides broader functionality in comparison to fine-grained service. It wraps one or more fine-grained services together into a coarse-grained service. It is fine to have more coarse-grained service operations.
4. Loosely Coupled
A tightly coupled system implies that the client and server logic are closely tied to one another, implying that if one interface changes, the other must be updated. Adopting a loosely coupled architecture tends to make software systems more manageable and allows simpler integration between different systems.
5. Capability to be synchronous and asynchronous
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Synchronous Web services are invoked over existing Web protocols by a client who waits for a response. Synchronous Web services are served by RPC- oriented messaging.
Asynchronous Web services are invoked over existing Web protocols by a client who does not wait for a response. The document-oriented messaging often used for asynchronous Web services. Asynchronous Web Service is a crucial factor in enabling loosely coupled system.
Servlets, HTTP, and XML/SOAP are used to implement synchronous or asynchronous endpoints.
6. Supports RPC
A web service supports RPC through offering services of its personal, equivalent to those of a traditional aspect.
. A web service is a web resource. We can access a web service using platform-independent and language-neutral web protocols, such as HTTP. HTTP ensures easy integration of heterogeneous environment. . A web service is typically registered. It can be located through a web service registry. A registry enables service consumers to find service that matches their needs. The service consumers may be human or other application. . A web service provides an interface (a web API) that can be called from another program. The application-to-application programming can be invoked from any application.
Architecture of Web Services The Web Services architecture describes how to instantiate the elements and implement the operations in an interoperable manner.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
The architecture of web service interacts among three roles: service provider, service requester, and service registry. The interaction involves the three operations: publish, find, and bind. These operations and roles act upon the web services artifacts. The web service artifacts are the web service software module and its description.
The service provider hosts a network-associable module (web service). It defines a service description for the web service and publishes it to a service requestor or service registry. These service requestor uses a find operation to retrieve the service description locally or from the service registry. It uses the service description to bind with the service provider and invoke with the web service implementation.
The following figure illustrates the operations, roles, and their interaction.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
WSDL
WSDL is an XML-based language for describing web services and how to access them.
WSDL stands for Web Services Description Language. WSDL was developed jointly by Microsoft and IBM. WSDL is an XML based protocol for information exchange in decentralized and distributed environments. WSDL is the standard format for describing a web service. WSDL definition describes how to access a web service and what operations it will perform. WSDL is a language for describing how to interface with XML- based services. o WSDL is an integral part of UDDI, an XML-based worldwide business registry. o WSDL is the language that UDDI uses. o WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.
UDDI
UDDI is an XML-based standard for describing, publishing, and finding web services. UDDI stands for Universal Description, Discovery, and Integration. UDDI is a specification for a distributed registry of web services. UDDI is platform independent, open framework. UDDI can communicate via SOAP, CORBA, and Java RMI Protocol. UDDI uses WSDL to describe interfaces to web services. UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
UDDI is an open industry initiative enabling businesses to discover each other and define how they interact over the Internet. SOAP
OAP is an XML-based protocol for exchanging information between computers SOAP is a communication protocol SOAP is for communication between applications. SOAP is a format for sending messages. SOAP is designed to communicate via Internet. SOAP is platform independent. SOAP is language independent. SOAP is simple and extensible. SOAP allows you to get around firewalls. SOAP will be developed as a W3C standard.
Advantages of Soap Web Services
o WS Security: SOAP defines its own security known as WS Security. o Language and Platform independent: SOAP web services can be written in any programming language and executed in any platform.
Disadvantages of Soap Web Services
Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be followed while developing the SOAP applications. So it is slow and consumes more bandwidth and resource.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.
XML-RPC:-
XML-RPC is among the simplest and most foolproof web service approaches that makes it easy for computers to call procedures on other computers.
XML-RPC permits programs to make function or procedure calls across a network. XML-RPC uses the HTTP protocol to pass information from a client computer to a server computer.
XML-RPC uses a small XML vocabulary to describe the nature of requests and responses. XML-RPC client specifies a procedure name and parameters in the XML request, and the server returns either a fault or a response in the XML response. L-RPC parameters are a simple list of types and content - structs and arrays are the most complex types available. XML-RPC has no notion of objects and no mechanism for including information that uses other XML vocabulary. With XML-RPC and web services, however, the Web becomes a collection of procedural connections where computers exchange information along tightly bound paths.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Fig: XML-RPC
Creating Web Service.
We'll follow these steps to create our simple Web Service:
Create the Web Service business logic.First, we need to write a Java class that implements the Web Service business logic. In this case, our business logic will be a 2simple Java class that simulates a stock quote service.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
Deploy the Java class to the SOAP server.Next, we need to turn the Java class into a Web Service. We'll show how to deploy the Java class to a SOAP server using the WASP deployment tool.
Generate client access classes. A client application uses a proxy object to access a Web Service. At request time, the proxy accepts a Java method call from the application and translates it into an XML message. At response time, the proxy receives the SOAP reply message, translates it into Java objects, and returns the results to the client application.
Client application development. The client application treats the proxy as a standard Java object that facilitates the communication with a Web Service.
Calling Web Service.
Now that we have built a server, the next step is to develop a client to call our web service.
We instantiate our XML-RPC client which will connect to our new server.
Once a connection is made, the request is sent to the server. We can easily create a custom client which manipulates the data returned from the server.
PROF. YOGESH DESHMUKH www.dacc.edu.in
DNYANSAGAR ARTS AND COMMERCE COLLEGE, BALEWADI,PUNE – 45
Subject: Advance PHP Subject code CA- 404 Class: SYBBA(CA)
PHP - DOM Parser Example
A HTML Dom parser written in PHP5.X versions. Dom Parser is very good at dealing with XML as well as HTML. Dom parser travels based on tree based and before access the data, it will load the data into dom object and it will update the data to the web browser. Below Example shows how to get access to the HTML data in web browser.
$html = '
Course details
Android | Gopal | Sairam | ||
Hadoop | Gopal | Graphic | Gopal | Satish |
Writer | Kiran | Amith | ||
Writer | Kiran | Vineeth |