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

php4 (2)

The document explains the concepts of classes and objects in PHP, detailing how classes serve as blueprints for creating objects with defined properties and methods. It covers the creation, access, and visibility of properties and methods, as well as inheritance, constructors, and destructors. Additionally, it touches on form handling in PHP, emphasizing its importance in web development for processing user input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

php4 (2)

The document explains the concepts of classes and objects in PHP, detailing how classes serve as blueprints for creating objects with defined properties and methods. It covers the creation, access, and visibility of properties and methods, as well as inheritance, constructors, and destructors. Additionally, it touches on form handling in PHP, emphasizing its importance in web development for processing user input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Class & Objects in PHP

Class-Object

Class is a blueprint for creating objects.It defines a set of properties


and methods to be used by the objects created from the class. An
object is an instance of a class, which means it has its own set of
properties and methods defined in the class. Class is a logical
entity. Object is a physical entity
Classes

A class is a blueprint used to create objects.It specifies the properties


(attributes)& methods(functions) that the class’s objects will posses.The class
keyword is used in PHP to define a class.
Ex: class Fruit {
// Properties
public $name;
public $color;

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

Note:
Properties: variables that store data within an object.
Methods:Function that define the behaviour of objects.
Visibility:keywords like public,private & protected control access to properties
& methods within & outside the class.
this keyword:Used within methods to refer the current object.

Objects:

An object is a class instance.We can create multiple objects from a class.Objects


are created based on classes,& each object has its own set of properties as well
as the ability to invoke the methods described in the class.The new keyword is
used to construct things.
Ex:
class Fruit {
// Properties
public $name;
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;
}
}
//creating an object of the fruit class
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color(); // O/P : Name: Apple
Color: Red

This class define a fruit object that has two property($color & $name) & two
methods(set_color() & get_color()).The &this keyword refer the current object
& is used to access its properties & methods.

Creating & Acccessing a class & object.

The procedure for creating & accessing the class & object in PHP are as follow:
Creating Class:
To create a class in PHP, use the class keyword followed by the name of the
class. The class name should be in CamelCase (i.e., the first letter of each word
is capitalized).

class MyClass {
// Properties and methods go here
}

Defining Properties and Methods


Properties are variables that belong to a class, and methods are functions that
belong to a class. To define properties, use the public, private,
or protected keyword followed by the property name. Similarly, to define
methods, use the public, private or protected keyword followed by the
method name and a pair of parentheses.
class MyClass {
public $property1;
private $property2;
protected $property3;
public function method1() {
// Code goes here
}
private function method2() {
// Code goes here
}
protected function method3() {
// Code goes here
}
}

Creating an Object
To create an object from a class, use the new keyword followed by the
class name and a pair of parentheses.
$object1 = new MyClass();

Accessing Properties and Methods


To access the properties and methods of an object, use the arrow operator (->)
followed by the property or method name. Keep in mind that you can only
access public and protected properties and methods from outside the class.
$object1->property1 = "Hello, world!";
echo $object1->property1; // Output: Hello, world!
$object1->method1();

A Simple PHP Class


Let's create a simple PHP class called Person with two properties
($firstName and $lastName) and two methods (getFullName() and sayHello()).

class Person {
public $firstName;
public $lastName;

public function getFullName() {


return $this->firstName . ' ' . $this->lastName;
}
public function sayHello() {
echo "Hello, my name is " . $this->getFullName() . ".";
}
}

$person1 = new Person();


$person1->firstName = "John";
$person1->lastName = "Doe";
$person1->sayHello(); // Output: Hello, my name is John Doe.

Object properties
Properties are variables that are defined within a class. These variables are
then used by the methods, objects of the class. These variables can be public,
protected or private. By default, the public is used. Each object has its own set
of properties with different values.

1.Declaring Properties:
Properties are declared within a class using the public, private or
protected keywords
class Person{
public $name;
private $age;
}
Accessing Properties:

➤ Outside the class: Public properties can be accessed using the


object name and the arrow operator (->):

$person1= new Person();


$person1->name = "Alice";
echo $person1->name; // Output: Alice

Private and protected properties cannot be accessed directly from


outside the class.

➤ Inside the class: All properties can be accessed using the $this
keyword:

public function introduce() {


echo "Hello, my name is". $this->name. "\n";
}

3. Visibility:

PHP visibility is a concept that defines how the properties and


methods of a class can be accessed. There are three visibility
keywords in PHP: public, private, and protected. They determine the
scope and accessibility of the class members. Here is a brief summary
of each visibility keyword:

➤ public: A public property or method can be accessed from


anywhere, including the same class, its subclasses, and any external
code.
➤ private: A private property or method can be accessed only from
within the same class that declared it. It is not visible to subclasses or
external code.
➤ protected: A protected property or method can be accessed from
within the same class and its subclasses, but not from external code.

Visibility keywords are used to enforce the principle of


encapsulation, which means hiding the ternal details of a class and
exposing only the relevant interface. This helps to maintain the
integrity and security of the class, and to prevent unwanted
interference or modification by external code.

4.Initializing Properties:

➤ Constructors: Used to initialize properties when an object is


created:

public function _ construct($name, $age) {


$this->name = $name;
$this->age = Sage;
}

5. Dynamic Properties:

PHP allows creating properties at runtime, even if they weren't


declared in the class. However, this practice is generally discouraged
in favour of explicit property declaration for better code readability
and maintainability.

Object methods

Object methods are functions defined within a class in PHP. These


methods represent the activity or actions that class objects can carry
out. Object methods are connected with a specific instance of a class
and can operate on that instance's properties. Methods, like
properties, can have various access modifiers (public, protected, and
private) to control their visibility from outside the class.
1. Declaring Methods:

Methods are declared within a class using the function keyword,


followed by the method name, parentheses, and optionally, a
visibility keyword:

class Person {
public function introduce() {
echo "Hello, my name is". $this->name . "\n";
}
}

2. Accessing Methods:

Methods are accessed using the object name, the arrow operator
(->), and the method name followed by parentheses:

$person1 = new Person();


$person1->introduce(); // Output: Hello, my name is (name set in
constructor).

3. $this Keyword:

Within a method, the $this keyword refers to the current object.

It's used to access the object's properties and call other methods of
the same object:

public function getAge() {


return $this->age; }

4. Visibility:

➤ Public methods: Can be accessed from anywhere.


➤ Private methods: Can only be accessed from within the class itself.
➤ Protected methods: Can be accessed from within the class and its
subclasses.
➤ Arguments and Return Values

5.Arguments and Return Values:

Methods can accept arguments as input and return values as output:

public function greet($greeting) {


echo $greeting. ",".$this->name. ".\n";
}

6. Special Methods:

Constructors: construct() is used to initialize objects when they are


created.
Destructors: destruct() is used to perform cleanup tasks when an
object is destroyed.

Overloading
When multiple methods are defined with same name, the concept is known as
method overloading. Overloading means creating same methods but with
different parameter.
PHP’s magic function _call() to achieve method overloading. If a class execute
_call(),then if an object of that class is called with a method that dosen’t exist
then _call() is called instead of that method.

Magic methods: magic methods are special methods that are called
automatically when certain conditions are met. There are several magic
methods in PHP. Every magic method follows certain rules
 Every magic method starts with a double underscore ( _ _ ).
 They are predefined and neither can be created nor removed.
 Magic methods have reserved names and their name should not be used
for other purposes.
Types of overloading
1.Property overloading:
Handled by the _ _ set() & _ _get() magic methods.For creating these
properties no separate line of code is needed.
_ _ set($name, $value) Method: This method is called when an inaccessible
variable or non-existing variable is tried to modify or alter.
_ _get($name) Method: This method gets called when an inaccessible
(private or protected ) variable or non-existing variables are used.
Example:
class Person {
private $data = [];
public function _ _set ($name, $value) {
$this->data[$name] = $value;
}
public function _ _get($name) {
return $this->data[$name] ?? null;
}
}

2.Method Overloading
Overloading is an Object-Oriented concept in which two or more methods
have the same method name with different arguments or parameters
(compulsory) and return type (not necessary). It can be done as Constructor
Overloading, Operator Overloading, and Method Overloading.

magic methods used to set methods dynamically are _ _call() .

Handled by the__call() magic method:

_ _call($name, Sarguments): Called when calling an undefined method.

Example:

class GFG {
public function __call($member, $arguments) {
$numberOfArguments = count($arguments);

if (method_exists($this, $function = $member.$numberOfArguments)) {


call_user_func_array(array($this, $function), $arguments);
}
}

private function multiply($argument1) {


echo $argument1;
}

private function multiply($argument1, $argument2) {


echo $argument1 * $argument2;
}
}
$class = new GFG;
$class->multiply(2);
$class->multiply(5, 7);
?> //O/P: 35

Inheritance
Inheritance is a fundamental object-oriented programming concept
in PHP where a class ( child class) can inherit properties and methods from
another class ( parent class). To implement inheritance in PHP, use
the extends keyword followed by the name of the parent class. The child
class inherits all public and protected properties and methods from the
parent class.

EX:<?php

//parent class

class Fruit {

public $name;

public $color;

public function __construct($name, $color) {

$this->name = $name;

$this->color = $color;
}

// (child class)

//Strawberry is inherited from Fruit

class Strawberry extends Fruit {

public function message() {

echo "Am I a fruit or a berry?The fruit is {$this->name} and the color is


{$this->color}.";

$strawberry = new Strawberry("Strawberry", "red");

$strawberry->message();

?> //O/P : Am I a fruit or a berry? The fruit is Strawberry and the color is red.

Types of Inheritance
1. Single Inheritance: A class can inherit from only one parent class. This is the
most common and straightforward type of inheritance.

Example 1:

class Animal {

public function eat() {

echo "Eating...\n";

}}

class Dog extends Animal {

public function bark() {

echo "Woof!\n";
}}

2. Multilevel Inheritance: A class can inherit from a parent class, which in turn
inherits from another parent class, creating a chain of inheritance.

Example 1:

class Vehicle {

public function move() {

echo "Moving...\n";

}}

class Car extends Vehicle {

public function drive() {

echo "Driving...\n";

}}

class SportsCar extends Car {

public function race() {

echo "Racing...\n";

}}

3. Multiple Inheritance(dimond problem..) (Not Directly Supported): PHP does


not support multiple inheritance in the traditional sense, where a class directly
inherits from multiple classes. However, you can achieve similar behavior using
interfaces. A class can implement multiple interfaces, effectively allowing it to
inherit method signatures from multiple sources. This is a form of "interface-
based" multiple inheritance.

Example:

interface Walkable {
public function walk();

interface Swimmable {

public function swim();

class Duck implements Walkable, Swimmable {

public function walk() {

// implementation}

public function swim() {

// implementation

}}

4. Hierarchical Inheritance: Multiple classes inherit from a single parent class,


forming a tree-like structure.

Example 1:
class Shape {
public $area;
}
class Circle extends Shape {
public function calculateArea() {
}
}
class Rectangle extends Shape {
public function calculateArea() {
}
}

5. Hybrid Inheritance (Combination of Multiple Types): Hybrid inheritance is a


combination of two or more types of inheritance. For example, a combination
of single and multiple inheritance or any other combination of the mentioned
types. Care should be taken to avoid issues like the diamond problem, which
can occur in languages that support multiple inheritance.

Example 1:
interface A {
// interface definition
}
interface B {
// interface definition
}
class C implements A, B {
// class implementation
}

Here, the class C implements both interfaces A and B.

Final keyword : The final keyword prevents child classes from overriding a
method or constant by prefixing the definition with final . If the class itself is
being defined final then it cannot be extended.
Note: Properties cannot be declared final: only classes, methods, and
constants may be declared as final.

Constructors
A constructor is a method that is automatically called when an object is
created from a class. It is used to initialize the object's properties.
Notice that the construct function starts with two underscores (_ _)!

If you create a _ _construct() function, PHP will automatically call this function
when you create an object from a class.
A constructor is declared similarly to other operations, except it has the same
name as the class, Though we can call the constructor directly, its primary
purpose is to be called when an formed.

After declaring a class, we must generate an object a specific individual who is


a member of the class-to work with. This is sometimes referred to as making
an instance or instantiating a class Using the new keyword, we construct an
object. We must give the class of which our object will be an instance, as well
as any parameters required by our constructor.
The following code declares class called classname with a constructor, and
then creates three objects of type classname:
Syntax of a constructor in PHP:
function _ _construct()
{
// initialize the object and its properties by assigning
//values
}

Ex1:
<?php
class Example
{
public function _ _construct() {
echo "Hello javatpoint";
}
}
$obj = new Example();
$obj = new Example();
?> // O/P : Hello javatpoint Hello javatpoint.

Destructor
A destructor is a method that is automatically called when an object is no
longer referenced or when the script is terminated. It is used to perform
cleanup tasks, release resources, or perform any actions before an object is
destroyed.
Notice that the destruct function starts with two underscores (_ _)!

Syntax of a Destructor in PHP:

class MyClass {
public function_destruct() {
// Cleanup code here
}
}
The destructor method is automatically called when an object is destroyed,
either explicitly the unset function or when the script finishes execution:
PHP's garbage collector automatically frees up memory occupied by objects
when they are no longer in use. While the destructor can be used for cleanup
tasks, it's not always necessary to explicitly define one.

PHP FORM HANDLING

Form processing in PHP is essential for web development because it allows you
to accept user input and process it on the server side. Form handling in PHP
refers to the process of capturing and processing user input submitted via
HTML forms.

It involves:

➤ HTML Forms: The foundation for collecting user input.


➤ PHP Scripts: Process the submitted form data.
➤ HTTP Methods: Determine how data is sent (GET or POST).
➤ $_GET and $_POST Superglobals: Access submitted data in PHP.

CREATING HTML FORM


The most important process in any dynamic Web site is handling an HTML form
with PHP. There are two phases involved: first, create the HTML form, and
then create the associated PHP script that will receive and handle the form
data.
If you're unfamiliar with the fundamentals of an HTML form, including the
many sorts of elements, consult an HTML resource.
An HTML form is created using the form tags and various elements for taking
input.

To Create an HTML Form:

1. Begin a new HTML document in your text editor or IDE, to be named


form.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple HTML Form</title>
<style type="text/css" title="text/css" media="all">
label {
font-weight: bold;
color: #300ACC;
}
</style>
<head>
<body>
<! --form.html-->

The document uses the same basic syntax for an HTML, page as in the previous
chapter. I have added some inline CSS (Cascading Style Sheets) in order to style
the form slightly (specifically, making label elements bold and blue).

CSS is the preferred way to handle many formatting and layout issues in an
HTML page.

2.Add the Initial Form Tag:


<form action="handle_form.php" method="post">

Since the action attribute dictates to which script the form data will go, you
should give it an appropriate name (handle_form to correspond with this page:
form.html) and the .php extension (since a PHP script will handle this form's
data).
3. Begin the HTML Form:

<fieldset><legend>Enter your information in the form below: </legend>

I'm using the fieldset and legend HTML tags because I like the way they make
the HTML form look (they add a box around the form with a title at the top).
This isn't pertinent to the form itself, though

4. Add Two Text Inputs:


<p><label>Name: <input type="text" name="name" size="20" maxlength="40"
></label></p>
<p><label>Email Address: <input type="text" name="email" size="40"
maxlength= "60" /> </label></p>

These are just simple text inputs, allowing the user to enter their name and
email address A. In case you are wondering, the extra space and slash at the
end of each input's tag are required for valid XHTML. With standard HTML,
these tags would conclude with maxlength="40"> instead. The label tags just
tie each textual label to the associated element.

5. Add a Pair of Radio Buttons:


<p><label for="gender">Gender: </label><input type="radio" name="gender"
value="M" /> Male <input type="radio" name= "gender" value="F" />
Female</p>

The radio buttons both have the same name, meaning that only one of the
two can be selected. They have different values, though.

6.Add a Pull-down Menu:


<p><label>Age: <select name="age">
< option value="0-29">under 30 </option>
< option value="30-60">between 30 & 60 </option>
</select>
</label></p>
The select tag starts the pull-down menu, and then each option tag will create
another line list of choices C. the

7. Add a Text Box for Comments:


<p><label>Comments: <textarea name="comments" rows="3"
cols="40"></textarea></label></p>
Textareas are different from text inputs; they are presented as a box , not as a
single line They allow for much more information to be typed and are useful
for taking user comments.

8. Complete the Form:

</fieldset>

<p align="center"><input type="submit" name="submit" value="Submit My


Information" /></p>

</form>

The first tag closes the fieldset that was opened in Step 3. Then a submit
button is created and centered using a p tag. Finally, the form is closed.

9. Complete the HTML Page:


</body>

</html>

10. Save the file as form.html,

place it in your Web directory, and view it in your Web browser

Handling HTML form data in PHP


Handling HTML form data in PHP involves several steps, from creating the form
in HTML to processing the data in PHP.

1. Creating the HTML Form

First, you need to create an HTML form that collects data from the user. Here's
an example of a simple form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Form</title>
</head>
<body>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
2. Processing the Form Data in PHP

Next, you need a PHP script to process the data. In this example, the form data
is sent to ‘process.php’. Here's what process.php might look like:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data using $_POST superglobal
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
// Validate form data (this is a basic example, you can add more validation)
if (!empty($name) && !empty($email) && filter_var($email,
FILTER_VALIDATE_EMAIL)) {
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
} else {
echo "Invalid form data.";
}
} else {
echo "Invalid request method.";
}
?>
Explanation of the PHP Script
1. Check Request Method: The script checks if the form was submitted using
the POST method.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
2. Retrieve Form Data: It retrieves the form data using the ‘$_POST’
superglobal.
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
3. Input: The htmlspecialchars function is used to convert special characters
to HTML entities .
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);

4. Validate Data: The script checks if the name and email are not empty and if
the email is valid.
if (!empty($name) && !empty($email) && filter_var($email,
FILTER_VALIDATE_EMAIL)) {
5. Process Data: If the data is valid, the script processes it. In this example, it
simply prints the data.
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";

To run this example:

1. Save the HTML code in a file named form.html.


2. Save the PHP code in a file named process.php.
3. Place both files in the root directory of your web server.
4. Open form.html in a web browser and fill out the form.
5. When you submit the form, it will send the data to process.php and
display the processed data.

You might also like