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

PHP UNIT4

The document provides an overview of classes and objects in PHP, detailing their definitions, syntax, and examples of creating and using them. It covers key concepts such as object properties, methods, inheritance, and traits, as well as the use of constructors and destructors. Additionally, it discusses form handling attributes in PHP, including the action, method, and encoding type for form submissions.

Uploaded by

divyashree
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

PHP UNIT4

The document provides an overview of classes and objects in PHP, detailing their definitions, syntax, and examples of creating and using them. It covers key concepts such as object properties, methods, inheritance, and traits, as well as the use of constructors and destructors. Additionally, it discusses form handling attributes in PHP, including the action, method, and encoding type for form submissions.

Uploaded by

divyashree
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

PHP&MY-SQL 1

Class and Objects in PHP


Classes:

• 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.

Programming Example for class:

<?php

class GeeksforGeeks

// Constructor

public function construct(){

echo 'The class "' . CLASS . '" was initiated!<br>';

// Create a new object


PHP&MY-SQL 2

$obj = new GeeksforGeeks;

?>

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:

Following is an example of how to create object using new operator.

Example:

<?php

class Person

{ public

$name; public

$age;

public function construct($name, $age) {

$this->name = $name;

$this->age = $age;

public function greet() {

echo "Hello, I am $this->name and I am $this->age years old.";

$person1 = new Person("John Doe", 30);

$person1->greet();

?>

OUTPUT:

Hello, I am John Doe and I am 30 years old.

Dept of MCA CDC, Mandya BHASKAR K S


Downloaded by Divyashree Nagabhushan
PHP&MY-SQL 9

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.

Types of Object Properties:


1. Visibility of properties:
o Public: Accessible from anywhere, both inside and outside the class.
o Private: Accessible only within the class where they are defined.
o Protected: Accessible within the class and by classes that extend it (subclasses).
2. Default Values: Properties can have default values or can be initialized via the constructor.

Example of Object Properties in PHP:

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;
}
}

$myCar = new Car("Toyota", "Corolla");

// Accessing public properties


echo $myCar->make; // Outputs: Toyota
echo $myCar->model; // Outputs: Corolla

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;
}

// Getter method to access private properties


PHP&MY-SQL 10
public function getDetails() {
return "Make: " . $this->make . ", Model: " . $this->model;
}
}

$myCar = new Car("Toyota", "Corolla");

// Trying to access private properties directly will result in an error


// echo $myCar->make; // Error: Cannot access private property

// Accessing private properties through a public method


echo $myCar->getDetails(); // Outputs: Make: Toyota, Model: Corolla

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;
}

// Protected method to return make and model


protected function getCarDetails() {
return "Make: " . $this->make . ", Model: " . $this->model;
}
}

class ElectricCar extends Car {


public function displayDetails() {
// Accessing protected property from parent class
return $this->getCarDetails();
}
}

$myCar = new ElectricCar("Tesla", "Model S");


echo $myCar->displayDetails(); // Outputs: Make: Tesla, Model: Model S

4. Default Property Values


You can initialize properties directly when declaring them or within the constructor.
php
class Car {
public $make = "Unknown";
public $model = "Unknown";

// Constructor
public function __construct($make = null, $model = null) {
if ($make) {
$this->make = $make;
PHP&MY-SQL 11
}
if ($model) {
$this->model = $model;
}
}
}

$car1 = new Car();


echo $car1->make; // Outputs: Unknown
echo $car1->model; // Outputs: Unknown

$car2 = new Car("Toyota", "Camry");


echo $car2->make; // Outputs: Toyota
echo $car2->model; // Outputs: Camry

```

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;
}
}

$calc = new Calculator();


echo $calc->add(5, 10); // Outputs: 15

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;

public function construct($name)


{
$this->name = $name;
}

public function getName()


{
return $this->name;
PHP&MY-SQL 12
}

public function makeSound()


{
echo 'The animal makes a sound.';
}
}

class Cat extends Animal


{
public function makeSound()
{
echo 'The cat meows.';
}
}

class Dog extends Animal


{
public function makeSound()
{
echo 'The dog barks.';
}
}
$cat = new Cat('Whiskers');
echo $cat->getName() . PHP_EOL; // Outputs: Whiskers
$cat->makeSound(); // Outputs: The cat meows.
$dog = new Dog('Buddy');
echo $dog->getName() . PHP_EOL; // Outputs: Buddy
$dog->makeSound(); // Outputs: The dog barks.?>

PHP supports two types of inheritance:

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;

public function construct($name)


{
$this->name = $name;
}

public function getName()


{
return $this->name;
}

public function move()


PHP&MY-SQL 13
{
echo $this->getName() . ' moves around.';
}
}

class Cat extends Animal


{

public function makeSound()


{
echo $this->getName() . ' says meow.';
}

$cat = new Cat('Whiskers');

$cat->move(); // Outputs: Whiskers moves around.

$cat->makeSound(); // Outputs: Whiskers says meow.

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;
}

$obj = new MyClass();


$obj->method1(); // Output: Trait1 method1
$obj->method2(); // Output: Trait2 method2
In the example above, the MyClass class uses both Trait1 and Trait2 using the use keyword. As a result,
instances of MyClass can access the methods defined in both traits.
By using traits, you can effectively share and reuse code across multiple classes in PHP, providing a form of
code reuse similar to multiple inheritance while avoiding its potential complexities.

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.

The magic methods:

• ` 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 {

public function call($name, $arguments)

{ if ($name === 'foo') {

switch (count($arguments)) {

case 1:

return $this->fooOneArg($arguments[0]);

case 2:

return $this->fooTwoArgs($arguments[0], $arguments[1]);

default:

throw new \InvalidArgumentException("Invalid number of arguments provided for method


$na
m
e
"
);

} else {

throw new \BadMethodCallException("Method $name does not exist");

private function fooOneArg($arg1) {

return "Called foo with one argument: $arg1";

private function fooTwoArgs($arg1, $arg2) {

return "Called foo with two arguments: $arg1 and $arg2";


PHP&MY-SQL 17
}

}
PHP&MY-SQL 18

$obj = new MyClass();

echo $obj->foo("arg1") . "\n";

echo $obj->foo("arg1", "arg2") . "\n";

?>

Explanation for Example:

• 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:

Called foo with one argument: arg1

Called foo with two arguments: arg1 and arg2

This approach provides a way to achieve method overloading-like behavior in PHP by dynamically handling
method calls with different argument counts.

Constructor and Destructor

In PHP, constructors and destructors are special methods used in object-oriented programming to initialize
and clean up object instances, respectively.

Constructor:

• A constructor is a method that gets called automatically when an object is created.


• In PHP, the constructor method is defined using the construct() magic method.
• The constructor method is useful for initializing object properties or performing any setup tasks
needed when an object is created.

Constructor Example:

<?php

class MyClass {

public function construct() {


PHP&MY-SQL 19

echo "Constructor called. Object created!";

$obj = new MyClass();

?>

OUTPUT:

Constructor called. Object created!

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 {

public function construct() {

echo "Constructor called. Object created!";

public function destruct() {

echo "Destructor called. Object destroyed!";

$obj = new MyClass(); // Output: Constructor called. Object created!

unset($obj); // Output: Destructor called. Object destroyed!

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.

PHP Form handling


Attributes of Form Tag:

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

<input type="text" name="address"/>


<span style="color:red;">*</span>
<br>
<br>
Email:
<input type="email" name="emailaddress"/>
<span style="color:red;">*</span>
<br>
<br>
Password:
<input type="password" name="password"/>
<span style="color:red;">*</span>
<br>
<br>
Gender:
<input type="radio"
value="Male"
name="gender"> Male
<input type="radio"
value="Female"
name="gender">Female
<br>
<br>
<input type="submit" value="Submit" name="submit" />
</form>
</fieldset>
<?php
if(isset($_POST['submit']))
{
if(!isset($error))
{
echo"<h1>INPUT RECEIVED</h1><br>";
echo "<table border='1'>";
echo "<thead>";
echo "<th>Parameter</th>";
echo "<th>Value</th>";
PHP&MY-SQL 25

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>

You might also like