php-module-4-notes
php-module-4-notes
• 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:
• 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.
```javascript
class Person {
constructor(name, age)
{ this.name = name; //
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.
```javascript class
Car {
constructor(brand) {
this.speed = 0; // Property
accelerate(amount) {
brake(amount) {
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;
$this->name = $name;
return $this->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;
{
PHP&MY-SQL 7
$this->name = $name;
return $this->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.
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
interface Scannable
// Traits
trait HasColor
PHP&MY-SQL 9
class MyColorfulClass
use HasColor;
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 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 {
switch (count($arguments)) {
case 1:
return $this->fooOneArg($arguments[0]);
case 2:
default:
} else {
}
PHP&MY-SQL 12
?>
• 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 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:
• 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.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<label for="name">Name:</label><br>
<label for="email">Email:</label><br>
<label for="message">Message:</label><br>
</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
if ($_SERVER["REQUEST_METHOD"] == "POST") {
PHP&MY-SQL 16
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
?>
• 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.
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,
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.).
<!DOCTYPE html>
PHP&MY-SQL 17
<html lang="en">
<head>
<title>HTML Form</title>
</head>
<body>
<h2>HTML Form</h2>
<label for="name">Name:</label><br>
<label for="email">Email:</label><br>
</form>
</body>
</html>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$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
// Process the form data (e.g., save to database, send email, etc.)
} else {
?>
• 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.