php4 (2)
php4 (2)
Class-Object
// 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:
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.
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
}
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();
class Person {
public $firstName;
public $lastName;
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:
➤ Inside the class: All properties can be accessed using the $this
keyword:
3. Visibility:
4.Initializing Properties:
5. Dynamic Properties:
Object methods
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:
3. $this Keyword:
It's used to access the object's properties and call other methods of
the same object:
4. Visibility:
6. Special Methods:
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.
Example:
class GFG {
public function __call($member, $arguments) {
$numberOfArguments = count($arguments);
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;
$this->name = $name;
$this->color = $color;
}
// (child class)
$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 {
echo "Eating...\n";
}}
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 {
echo "Moving...\n";
}}
echo "Driving...\n";
}}
echo "Racing...\n";
}}
Example:
interface Walkable {
public function walk();
interface Swimmable {
// implementation}
// implementation
}}
Example 1:
class Shape {
public $area;
}
class Circle extends Shape {
public function calculateArea() {
}
}
class Rectangle extends Shape {
public function calculateArea() {
}
}
Example 1:
interface A {
// interface definition
}
interface B {
// interface definition
}
class C implements A, B {
// class implementation
}
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.
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 (_ _)!
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.
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:
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.
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:
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
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.
The radio buttons both have the same name, meaning that only one of the
two can be selected. They have different values, though.
</fieldset>
</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.
</html>
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>";