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

php-module-4-notes

The document provides an overview of classes and objects in PHP, detailing their definitions, syntax, and examples of how to create and use them. It covers key concepts such as object properties, methods, inheritance, and the use of constructors and destructors. Additionally, it discusses HTML forms, including their structure, attributes, and a simple example of form handling in PHP.

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-module-4-notes

The document provides an overview of classes and objects in PHP, detailing their definitions, syntax, and examples of how to create and use them. It covers key concepts such as object properties, methods, inheritance, and the use of constructors and destructors. Additionally, it discusses HTML forms, including their structure, attributes, and a simple example of form handling in PHP.

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 3

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:

• Object properties, also known as fields or attributes, represent the data associated with an object.
These are the characteristics or qualities that describe the object's state.
• Properties are defined within a class and are accessed using dot notation (`object.property`) after an
object is instantiated from that class.
• Properties can have different data types, such as strings, numbers, booleans, arrays, or even other
objects.

Example (in JavaScript):

```javascript

class Person {

constructor(name, age)

{ this.name = name; //

Property this.age = age; //

Property

const person1 = new Person("Alice", 30);

console.log(person1.name); // Accessing property

console.log(person1.age); // Accessing property

```

2. **Object Methods**:

- Object methods are functions defined within a class that operate on the object's properties or perform
PHP&MY-SQL 4
certain actions associated with the object.
PHP&MY-SQL 5

- Methods define the behavior of an object and typically manipulate the object's state (properties) in some
way.

- Methods are accessed using dot notation (`object.method()`) after an object is instantiated from the class.

Example (in JavaScript):

```javascript class

Car {

constructor(brand) {

this.brand = brand; // Property

this.speed = 0; // Property

accelerate(amount) {

this.speed += amount; // Method modifying property

brake(amount) {

this.speed -= amount; // Method modifying property

const myCar = new Car("Toyota");

myCar.accelerate(50); // Invoking method

console.log(myCar.speed); // Accessing property modified by method

myCar.brake(20);

console.log(myCar.speed);

```
PHP&MY-SQL 6

In summary, object properties represent the state of an object, while object methods define the behavior or
actions that an object can perform. Together, properties and methods encapsulate the data and behavior of
objects, promoting encapsulation, abstraction, and modularity in object-oriented programming.

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;

public function makeSound()

echo 'The animal makes a sound.';

class Cat extends Animal


PHP&MY-SQL 7

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)

{
PHP&MY-SQL 7

$this->name = $name;

public function getName()

return $this->name;

public function move()

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.
PHP&MY-SQL 8

Instead, they define a set of methods that can be added to a class. A class can include multiple traits to
inherit their methods.

Example:

interface Printable

public function printDocument();

interface Scannable

public function scanDocument();

class Printer implements Printable

public function printDocument()

echo 'Printing document...';

class Scanner implements Scannable

public function scanDocument()

echo 'Scanning document...';

// Traits

trait HasColor
PHP&MY-SQL 9

public function setColor($color)

echo 'Setting color to: ' . $color;

class MyColorfulClass

use HasColor;

$printer = new Printer();

$printer->printDocument(); // Outputs: Printing document...

$scanner = new Scanner();

$scanner->scanDocument(); // Outputs: Scanning document...

$colorfulObject = new MyColorfulClass();

$colorfulObject->setColor('red'); // Outputs: Setting color to: red

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 10

• 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 11
}

}
PHP&MY-SQL 12

$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 13

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 14

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

HTML FORMS:

Sure, here are some key points about HTML forms:

• Form Structure: HTML forms are created using the `<form>` element, which contains various
input elements like text fields, checkboxes, radio buttons, dropdown lists, etc.
• Method Attribute: The method attribute of the `<form>` element specifies how form data should be
submitted. It can be set to either "GET" or "POST" method. The "GET" method appends form data
to the URL, while the "POST" method sends form data in the request body.
• Action Attribute: The action attribute of the `<form>` element specifies the URL of the script that
will process the form data when the form is submitted.
• Input Elements: Input elements are used to collect data from the user. Some common input types
include text, password, email, number, checkbox, radio, file, etc.
• Label Element: The `<label>` element is used to associate a text label with an input element. This
improves accessibility and usability for users, especially those using assistive technologies.
• Name Attribute: Each input element should have a unique name attribute. When the form is
submitted, the data is sent to the server using the name attribute as the key and the user's input as the
value.
• Required Attribute: The required attribute can be added to input elements to make them
mandatory. Users will be prompted to fill in these fields before submitting the form.
• Validation: HTML5 introduced new input types and attributes for client-side form validation, such
as `pattern`, `min`, `max`, `step`, etc. Additionally, JavaScript can be used for more advanced form
validation.
• Submit Button: The `<input type="submit">` element or `<button type="submit">` element is used
to submit the form data to the server.
• Reset Button: The `<input type="reset">` element resets all form fields to their default values when
clicked.
• Placeholder Attribute: The placeholder attribute adds temporary instructional text to an input field,
providing hints or examples of the expected input format.
• Form Control Attributes: Other attributes like `disabled`, `readonly`, `autocomplete`, etc., can be
used to control the behaviour of form elements.
PHP&MY-SQL 15

These are some essential points to consider when working with HTML forms. Understanding these concepts
will help you create effective and user-friendly forms for your web applications.

Simple Example for HTML FORMS:

<!DOCTYPE html>

<html lang="en">

<head>

<title>PHP Form Example</title>

</head>

<body>

<h2>PHP Form Example</h2>

<form method="POST" action="process_form.php">

<label for="name">Name:</label><br>

<input type="text" id="name" name="name"><br>

<label for="email">Email:</label><br>

<input type="email" id="email" name="email"><br>

<label for="message">Message:</label><br>

<textarea id="message" name="message"></textarea><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

This HTML code creates a simple form with fields for the user to input their name, email, and a message. The
form uses the POST method to send the data to a PHP script named `process_form.php` for processing.

PHP SCRIPT FOR ABOVE EXAMPLE

<?php

// Check if the form is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {
PHP&MY-SQL 16

// Retrieve form data

$name = $_POST['name'];

$email = $_POST['email'];

$message = $_POST['message'];

// Process the data (e.g., save to database, send email, etc.)

// For this example, let's just print the data

echo "Name: $name<br>";

echo "Email: $email<br>";

echo "Message: $message<br>";

?>

• This PHP script checks if the form is submitted using the `$_SERVER["REQUEST_METHOD"]`
variable.
• If the form is submitted via the POST method, it retrieves the form data using the `$_POST`
superglobal array and processes it.
• In this example, the data is simply printed back to the user, but you can perform any necessary
processing such as saving the data to a database, sending an email, etc.

Handling the HTML Form data in php:

To handle HTML form data in PHP, you need to create a PHP script that receives the form submission and
processes the data sent from the form. Here's how you can handle form data in PHP,

1. Create an HTML form with the appropriate form fields.

2. Set the form's method attribute to "POST" or "GET" depending on how you want to send the form data.

3. Specify the action attribute of the form to point to the PHP script that will process the form data.

4. In the PHP script, use the `$_POST` or `$_GET` superglobal arrays to access the form data submitted by
the user.

5. Process the form data as needed (e.g., validate inputs, perform calculations, interact with a database, etc.).

Simple example for handling the html form data in php

<!DOCTYPE html>
PHP&MY-SQL 17

<html lang="en">

<head>

<title>HTML Form</title>

</head>

<body>

<h2>HTML Form</h2>

<form method="POST" action="process_form.php">

<label for="name">Name:</label><br>

<input type="text" id="name" name="name"><br>

<label for="email">Email:</label><br>

<input type="email" id="email" name="email"><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

PHP SCRIPT FOR ABOVE EXAMPLE

<?php

// Check if form is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Retrieve form data using $_POST superglobal

$name = $_POST['name'];

$email = $_POST['email'];

// Validate form data (e.g., check for empty fields, validate email format, etc.)

// For simplicity, let's just check if name and email are provided

if (!empty($name) && !empty($email)) {

// Process the form data (e.g., save to database, send email, etc.)

// For this example, let's just echo the submitted data


PHP&MY-SQL 18

echo "Name: $name<br>";

echo "Email: $email<br>";

} else {

// If required fields are empty, display an error message

echo "Please provide both name and email.";

?>

• In this example, when the user submits the form, the data is sent to the `process_form.php` script
using the POST method.
• The PHP script retrieves the form data from the `$_POST` superglobal array, validates it, and
processes it accordingly.
• Finally, the script displays the submitted data or an error message if required fields are empty.

You might also like