PHP UNIT4
PHP UNIT4
• Classes are the blueprints of objects. One of the big differences between functions and classes is that
a class contains both data (variables) and functions that form a package called an: ‘object’.
• Class is a programmer-defined data type, which includes local methods and local variables.
• Class is a collection of objects. Object has properties and behaviour.
Syntax: We define our own class by starting with the keyword ‘class’ followed by the name you want to
give your new class.
<?php
class person {
?>
Note: We enclose a class using curly braces ( { } ) … just like you do with functions. Given below are the
programs to elaborate the use of class in Object Oriented Programming in PHP. The programs will illustrate
the examples given in the article.
<?php
class GeeksforGeeks
// Constructor
?>
Object in PHP:
An Object is an individual instance of the data structure defined by a class. We define a class once and then
make many objects that belong to it. Objects are also known as instances.
Creating an Object:
Example:
<?php
class Person
{ public
$name; public
$age;
$this->name = $name;
$this->age = $age;
$person1->greet();
?>
OUTPUT:
Object methods and Object Properties: Object methods and object properties are fundamental concepts in
object-oriented programming (OOP). They are used to encapsulate behavior (methods) and data (properties)
within objects.
Object Properties:
In PHP, object properties refer to the variables that are declared within a class. These properties are used to
store data or attributes that belong to an instance (object) of the class. Object properties are accessed using
the -> operator.
1. Public Property
Public properties are directly accessible from outside the class.
php
class Car {
public $make;
public $model;
// Constructor
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}
}
2. Private Property
Private properties can only be accessed inside the class. They cannot be accessed directly from outside the
class.
php
class Car {
private $make;
private $model;
// Constructor
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}
3. Protected Property
Protected properties can be accessed within the class and by subclasses (child classes) but not from outside.
php
Copy
class Car {
protected $make;
protected $model;
// Constructor
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}
// Constructor
public function __construct($make = null, $model = null) {
if ($make) {
$this->make = $make;
PHP&MY-SQL 11
}
if ($model) {
$this->model = $model;
}
}
}
```
OBJECT METHODS
Object methods are functions defined within a class. You access these methods using the -> operator.
php
class Calculator {
public function add($a, $b) {
return $a + $b;
}
}
INHERITANCE:
A child class can inherit properties and methods from a parent class, and you can also override or extend
their behaviour in the child class. It is achieved by extends keyword.
Example:
<?php
class Animal
{
protected $name;
Single Inheritance: A single child class can inherit from a single parent class. This is the most common
form of inheritance, where a child class extends a single parent class to inherit its properties and methods.
Example:
class Animal
protected $name;
Multiple Inheritance:
PHP does not support multiple inheritance directly, but it can be simulated using interfaces or traits.
Interfaces: A class can implement multiple interfaces, which allows it to define a set of methods that must
be implemented by the class. Interfaces define a contract for a class, specifying the methods that the class
must provide, but they do not provide any implementation details.
Traits: A trait is a way to reuse code across multiple classes. It is similar to a mixin in other languages.
Traits cannot be instantiated on their own, and they do not have any properties or methods of their own.
Instead, they define a set of methods that can be added to a class. A class can include multiple traits to
inherit their methods.
Traits in PHP allow you to define methods that can be reused in multiple classes. You can think of traits as a
set of methods that can be mixed into classes, providing a way to share code across different class
hierarchies. Traits enable you to achieve code reuse and composition while avoiding the potential issues of
multiple inheritance.
Here's an example of how traits work in PHP
trait Trait1 {
public function method1() {
echo "Trait1 method1";
}
}
PHP&MY-SQL 14
trait Trait2 {
public function method2() {
echo "Trait2 method2";
}
}
class MyClass {
use Trait1, Trait2;
}
In the below example program there are multiple interfaces that are very much helpful in implementing the
multiple inheritances. In the below-listed PHP program’s example, there are two interfaces with the names
“B1” and “C1” which are actually playing the role of the base classes and there is always a child class with
the name “Multiple1” and we are now invoking all the other functions by using the “pavan” object.
Code:
<?php
interface C1 {
public function insideC1();
}
interface B1 {
public function insideB1();
}
class Multiple1 implements B1, C1 {
// Function of the interface B1
function insideB1() {
echo "\n Hey now you are in the interface B1";
}
// Function of the interface C1
PHP&MY-SQL 15
function insideC1() {
echo "\nHi buddy !! Now you are in the interface C1";
}
public function insidemultiple1()
{
echo "\nHeyaa You are in the inherited class";
}
}
$Naruto = new multiple1();
$Naruto->insideC1();
$Naruto->insideB1();
$Naruto->insidemultiple1();
?>
Output:
OVERLOADING:
• In PHP, method overloading typically refers to the ability to define multiple methods in a class with
the same name but different parameter lists.
• Unlike some other languages like Java or C++, PHP doesn't support method overloading in this
manner out-of-the-box.
• PHP does offer a form of overloading through the use of magic methods such as ` call()` and
` callStatic()`.
• These methods allow you to intercept calls to undefined methods and handle them dynamically.
• While this doesn't strictly adhere to the concept of method overloading as seen in other languages, it
provides a mechanism for achieving similar functionality.
• ` call()`: This method is triggered when invoking inaccessible methods in an object context.
PHP&MY-SQL 16
• callStatic()`: Similar to ` call()`, but triggered when invoking inaccessible methods in a static
context.
Here's a simple example demonstrating the use of ` call()` for method overloading-like behavior:
<?php
class MyClass {
switch (count($arguments)) {
case 1:
return $this->fooOneArg($arguments[0]);
case 2:
default:
} else {
}
PHP&MY-SQL 18
?>
• The `MyClass` defines the ` call()` magic method, which is invoked when calling undefined
methods.
• Inside ` call()`, we check if the method being called is `foo`, and then route the call based on the
number of arguments provided.
• Depending on the number of arguments, the call is delegated to `fooOneArg()` or `fooTwoArgs()`
private methods.
• These private methods are the actual implementations of `foo` with different argument counts.
OUTPUT:
This approach provides a way to achieve method overloading-like behavior in PHP by dynamically handling
method calls with different argument counts.
In PHP, constructors and destructors are special methods used in object-oriented programming to initialize
and clean up object instances, respectively.
Constructor:
Constructor Example:
<?php
class MyClass {
?>
OUTPUT:
Destructor:
• A destructor is a method that gets called automatically when an object is destroyed or goes out of
scope.
• In PHP, the destructor method is defined using the “ destruct()” magic method.
• The destructor method is useful for releasing resources or performing cleanup tasks before an object
is destroyed.
Destructor Example:
class MyClass {
OUTPUT Explanation:
In the above example, when $obj goes out of scope (either explicitly unset or when script execution ends),
the destructor “ destruct()” is automatically called.
PHP&MY-SQL 20
• It's important to note that in PHP, if a class does not explicitly define a constructor, a default
constructor is provided.
• Similarly, if a class does not define a destructor, PHP will automatically handle cleanup tasks when
the object is destroyed.
• However, it's generally considered good practice to explicitly define both constructor and destructor
methods in your classes when needed.
Attribute Description
name or
It specifies the name of the form and is used to identify individual forms.
id
It specifies the location to which the form data has to be sent when the form is
action
submitted.
It specifies the HTTP method that is to be used when the form is submitted. The
method possible values are get and post. If get method is used, the form data are visible
to the users in the url. Default HTTP method is get.
encType It specifies the encryption type for the form data when the form is submitted.
novalidate It implies the server not to verify the form data when the form is submitted.
Controls used in forms: Form processing contains a set of controls through which the client and server
can communicate and share information. The controls used in forms are:
Textbox: Textbox allows the user to provide single-line input, which can be used for getting values
such as names, search menu and etc.
Textarea: Textarea allows the user to provide multi-line input, which can be used for getting values
such as an address, message etc.
DropDown: Dropdown or combobox allows the user to provide select a value from a list of values.
Radio Buttons: Radio buttons allow the user to select only one option from the given set of options.
CheckBox: Checkbox allows the user to select multiple options from the set of given options.
Buttons: Buttons are the clickable controls that can be used to submit the form.
Creating a simple HTML Form: All the form controls given above is designed by using the input tag
PHP&MY-SQL 21
based on the type attribute of the tag. In the below script, when the form is submitted, no event
handling mechanism is done. Event handling refers to the process done while the form is submitted.
These event handling mechanisms can be done by using javaScript or PHP. However, JavaScript
provides only client-side validation. Hence, we can use PHP for form processing.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<form id="form1" method="post">
FirstName:
<input type="text" name="firstname" required/>
<br>
<br>
LastName
<input type="text" name="lastname" required/>
<br>
<br>
Address
<input type="text" name="address" required/>
<br>
<br>
Email Address:
<input type="email" name="emailaddress" required/>
<br>
<br>
Password:
<input type="password" name="password" required/>
<br>
<br>
<input type="submit" value="Submit”/>
</form>
PHP&MY-SQL 22
</body>
</html>
Form Validation: Form validation is done to ensure that the user has provided the relevant information.
Basic validation can be done using HTML elements. For example, in the above script, the email
address text box is having a type value as “email”, which prevents the user from entering the
incorrect value for an email. Every form field in the above script is followed by a required attribute,
which will intimate the user not to leave any field empty before submitting the form. PHP methods
and arrays used in form processing are:
isset(): This function is used to determine whether the variable or a form control is having a value or
not.
$_GET[]: It is used the retrieve the information from the form control through the parameters sent in
the URL. It takes the attribute given in the url as the parameter.
$_POST[]: It is used the retrieve the information from the form control through the HTTP POST
method. IT takes name attribute of corresponding form control as the parameter.
$_REQUEST[]: It is used to retrieve an information while using a database.
Form Processing using PHP: Above HTML script is rewritten using the above mentioned functions
and array. The rewritten script validates all the form fields and if there are no errors, it displays the
received information in a tabular form.
Example:
<?php
if (isset($_POST['submit']))
{
if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||
(!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||
(!isset($_POST['password'])) || (!isset($_POST['gender'])))
{
$error = "*" . "Please fill all the required fields";
}
else
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
PHP&MY-SQL 23
$gender = $_POST['gender'];
}
}
?>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<h1>Form Processing using PHP</h1>
<fieldset>
<form id="form1" method="post" action="form.php">
<?php
if (isset($_POST['submit']))
{
if (isset($error))
{
echo "<p style='color:red;'>"
. $error . "</p>";
}
}
?>
FirstName:
<input type="text" name="firstname"/>
<span style="color:red;">*</span>
<br>
<br>
Last Name:
<input type="text" name="lastname"/>
<span style="color:red;">*</span>
<br>
<br>
Address:
PHP&MY-SQL 24
echo "</thead>";
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>".$firstname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last Name</td>";
echo "<td>".$lastname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Address</td>";
echo "<td>".$address."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Email Address</td>";
echo "<td>" .$emailaddress."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Password</td>";
echo "<td>".$password."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Gender</td>";
echo "<td>".$gender."</td>";
echo "</tr>";
echo "</table>";
}
}
?>
</body>
</html>