0% found this document useful (0 votes)
59 views13 pages

Unit-04 Php Class and Object

This document provides an overview of classes and objects in PHP, explaining the concepts of classes as blueprints for objects and the role of constructors and destructors. It covers object properties, methods, visibility, and inheritance, detailing how to create and manage classes and their instances. Additionally, it discusses form handling in PHP, including how to create and process HTML forms using GET and POST methods.

Uploaded by

ganavig291
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views13 pages

Unit-04 Php Class and Object

This document provides an overview of classes and objects in PHP, explaining the concepts of classes as blueprints for objects and the role of constructors and destructors. It covers object properties, methods, visibility, and inheritance, detailing how to create and manage classes and their instances. Additionally, it discusses form handling in PHP, including how to create and process HTML forms using GET and POST methods.

Uploaded by

ganavig291
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit-04

CLASS AND OBJECTS IN PHP


What is a class?
A class is a blueprint or template used to create an object.class is a programmer defined
data type. Class is a group of objects which have common properties. To create a class
use the keyword class followed by class name.
Syntax:
<?php
class class name
{
//class properties and method goes here
}
What is an object?
An object is an instance of class or it is an entity that has state and behaviour is known
as object. Using object we can access the class members and properties.
Syntax:
$obj=new classname():

Creating An Class And Object In Php

• Use class keyword followed by desired class name


• Class can have constructor.[a constructor is a method which is followed by
function]and are used to initialize object properties when its created.
• When u call an object constructor is automatically executed.

Example:
<?php
class person
{
//properties
public $name;
public $age;
//constructor
function __construct()
{
$this->name=$name;
$this->age=$age;
}
}
//object
$person=new person(“ram”,20);
echo $person->name;
echo $person->age;
?>
Output:
ram
20

Example:
<?php
class car
{
public $brand;
public $model;
public function drive()
{
echo” driving the this->brand and $this->model.”;
}
}
$mycar=new car();
$mycar->brand=”Toyota” ; //setting the brand property
$mycar->model=’Innova”; //setting the model property
$mycar->drive(); //access the method of the object
?>
Output: driving the Toyota and Innova.

Note:
• the pseudo variable $this is available when a method is called from within
an object context.
• $this refers to the current object within its method or calling object.
• setname and getname are functions defined inside a class and are also
called as method.

Object Properties:

Properties are variables declared within a class and assigned to particular objects
within class. They store data that represents the object's attributes or qualities. Each
object has its own 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;
}

2. Accessing Properties:
➤ Outside the class: Public properties can be accessed using the object name and the
arrow operator (→):
$person1 =new Person();
$person 1 name = "jhon";
echo Sperson1 name; // Output: jhon
Private and protected properties cannot be accessed directly from outside the class.

➤ Inside the class: All properties can be accessed using the $this keyword .

public function introduce()


{
echo "Hello, my name is $this->name "\n";
}

3. Visibility:
PHP visibility is a concept that defines how the properties and methods of a class can be
accessed. There are three visibility keywords in PHP public, private, and protected They
determine the scope and accessibility of the class members Here is a brief summary of
each visibility keyword :

➤ public: A public property or method can be accessed from anywhere, including the
same class, its subclasses, and any external code.
➤ private: A private property or method can be accessed only from within the same
class that declared it. It is not visible to subclasses or external code
➤ protected: A protected property or method can be accessed from within the same
class and its subclasses, but not from external code.
Visibility keywords are used to enforce the principle of encapsulation, which means
hiding the internal details of a class and exposing only the relevant interface. This helps
to maintain the integrity and security of the class, and to prevent unwanted interference
or modification by external code.
4. Initializing Properties:
➤ Constructors: Used to initialize properties when an object is created
public function construct($name, Sage) (
$this ->name = $name;
$this->age =Sage;
5. Dynamic Properties:
PHP allows creating properties at runtime, even if they weren't declared in the class.
However, this practice is generally discouraged in favour of explicit property declaration
for better cade readability and maintainability.

OBJECT METHODS :

Object methods are functions defined within a class in PHP. These methods represent
the activity or actions that class objects can carry out. Object methods are connected
with a specific instance of a class and can operate on that instance's properties.
Methods, like properties, can have various access modifiers (public, protected, and
private) to control their visibility from outside the class.

1. Declaring Methods:
Methods are declared within a claas using the function keyword, followed by the
method name, parentheses, and optionally, a visibility keyword
class Person
{(

public function introduce() {


echo "Hello, my name is". $this-> name.";
}
}

2. Accessing Methods:
Methods are accessed using the object name, the arrow operator (→), and the method
name followed by parentheses:
$person1 =new Person();
$person 1->introduce(); // Output: Hello, my name is (name set in constructor).

3.$this Keyword:
Within a method, the $this keyword refers to the current object.
It's used to access the object's properties and call other methods of the same object:
public function getAge()
{
return $this->age;
}

4. Visibility:
➤ Public methods: Can be accessed from anywhere.
➤ Private methods: Can only be accessed from within the class itself.
➤ Protected methods: Can be accessed from within the class and its subclasses.
➤ Arguments and Return Values

5. Arguments and Return Values:


Methods can accept arguments as input and return values as output.
public function greet($greeting)
{
echo $greeting.",".$this->name. "\n";
}

6. Special Methods:
➤ Constructors. construct() is used to initialize objects when they are created.
➤ Destructors: destruct() is used to perform cleanup tasks when an object is destroyed
➤ Other magic methods PHP has several other special methods with double
underscores that have specific behaviors (eg, toString(), call(), clone()).
OVERLOADING:

In PHP, overloading refers to the ability to dynamically create properties and methods at
runtime using magic methods. It's different from traditional overloading in languages
like Java or C++ (where methods with the same name but different parameters coexist).
PHP doesn't support method overloading by signature. Instead, it uses magic methods to
handle access to undefined properties or methods.

Types of Overloading in PHP


PHP supports two main types of overloading via magic methods:
1. Property Overloading:
This occurs when you try to get, set, check, or unset an inaccessible or non-existent
property.
Magic methods used:
__get($name)
__set($name, $value)
__isset($name)
__unset($name)

Example:
<?php
class fruit
{
public $name;
public $color;
function __set($name)
{
$this->name=$name;
}
function __get()
{
echo $this->name.”<br/>”;
}
function __set($color)
{
$this->color=$color;
}
function __get()
{
echo $this->color.”<br/>”;
}
}
$fruit1=new fruit();
$fruit1->name=”apple”;
$fruit1->color=”red”;
echo $fruit->name;
echo $fruit->color;
?>
2.Method Overloading:
This occurs when you call a method that does not exist. You can handle this with the
__call() or __callStatic() magic methods.
• __call($name, $arguments) – For non-static method calls.
• __callStatic($name, $arguments) – For static method calls.

Example:
class Math {
public function __call($name, $arguments) {
if ($name == 'add') {
return array_sum($arguments);
}
}
}

$m = new Math();
echo $m->add(5, 10, 15); // Outputs: 30

INHERITANCE:
Inheritance: “ Taking the properties of one class into another is called inheritance.”

Inheritance is a fundamental concept in object-oriented programming that


allows us to define a new class based on an existing class. The new class
inherits the properties and methods of the existing class and can also add new
properties and methods of its own. Inheritance promotes code reuse, simplifies
code maintenance, and improves code organization.
• The class which inherits the members of another class is called derived class
• The class whose members are inherited is called base class.
• The derived class is the specialized class for the base class.

SYNTAX:
class BaseClassName DerivedClassName
{
Variables;
Methods()
{
}
}

TYPES OF INHERITANCE:
1. Single Inheritance.
2. Multilevel Inheritance.
3. Hierarchical Inheritance.
4. Multiple Inheritance.

1. Single Inheritance: When one class inherits another class, it is known as single
level inheritance.or In single inheritance, a single derived class inherits from a single
base class.
Example:
<?php
class animal
{
public $name;
public function __construct($name)
{
$this->name=$name;
}
public function speak()
{
echo "i am san animal named $this->name.";
}
}

class dog extends animal


{
public function bark()
{
echo "i am a dog and i can bark.woof";
}
}
$dog=new dog(“max”);
$dog->speak();
$dog->bark();
?>
Output:
I am an animal named max
Iam a dog and I can bark.woof.

2. Multilevel Inheritance:

When one class inherits another class which is further inherited by another class, it
is known as multi level inheritance.

Example:
<?php
class Animal {
public function sound() {
echo "Animals make sound\n";
}
}

class Dog extends Animal {


public function bark() {
echo "Dog barks\n";
}
}

class Puppy extends Dog {


public function weep() {
echo "Puppy weeps\n";
}
}

$myPuppy = new Puppy();


$myPuppy->sound();
$myPuppy->bark();
$myPuppy->weep();
?>
3. Multilevel Inheritance(Not Directly Supported).

Multilevel inheritance in PHP occurs when a class inherits from a parent class, and
then another class inherits from that derived class, creating a chain of inheritance.
While PHP supports inheritance, it only allows for single inheritance, meaning a
class can inherit from only one parent class. This limits the direct implementation of
true multilevel inheritance in PHP.
This is a form of “interface-based” multiple inheritance.
Example:
<?php
class a
{
public function sayhello()
{
echo”hello from a”;
}
}
class b
{
public function saybye()
{
echo”bye from b”;
}
}
interface c extends a,b
{
public function sayhi()
}
class d implemts c
{
public function sayhello()
{
echo”hello from d”;
}
public function saybye()
{
echo”bye from d”;
}
public function sayhi()
{
echo”hi from d”;
}
}
$d=new d();
$d->sayhello();
$d->saybye();
$d->sayhi();
?>
Output:
Hello from d
Bye from d
Hi from d

Note:Php does not support multiple inheritance directly, but it can be achieved by
using interface. Interface are abstract classes that define a set of methods that the
implementing classes must provide.

4.Hierarchical Inheritance: In hierarchical inheritance, multiple derived


classes inherit from a single base class. A base class that serves as a parent class for
two or more derived classes.
Example:
<?php
class Fruit {
public $name;
public function __construct($name) {
$this->name = $name;
}
}

class Apple extends Fruit {


public function getType() {
return "Apple";
}
}

class Orange extends Fruit {


public function getType() {
return "Orange";
}
}

$apple = new Apple("Apple");


$orange = new Orange("Orange");
echo $apple->getType(); // Output: Apple
echo $orange->getType(); // Output: Orange
?>
CONSTRUCTOR AND DESTRUCTOR

CONSTRUCTOR:

A constructor is a special method of the class which gets automatically invoked


whenever an instance of the class is created. Like methods, a constructor also contains
the collection of instructions that are executed at the time of Object creation. It is used to
assign initial values to the data members of the same class.
Or
“A constructor is a method that is automatically called when an object is created from a
class.”
Syntax:
<?php
class ClassName {
public function __construct() {
// Constructor code here
}
}
?>

Example:
<?php
class Car {
public $model;
public $color;
// Constructor
public function __construct($model, $color)
{
$this->model = $model;
$this->color = $color;
}

public function display()


{
echo "Model: $this->model, Color: $this->color";
}
}
$myCar = new Car("Tesla", "Red");
$myCar->display();
?>

Output
Model: Tesla, Color: Red
In this example:
• The constructor __construct() is used to initialize the properties $model and
$color when an object of the Car class is created.
• When the object $myCar is created, the constructor is called automatically with
“Tesla” and “Red” passed as arguments, thus initializing the car’s properties.
• The display() method is used to print the car details.
DESTRUCTOR
A destructor is a special method in PHP that is automatically called when an object is
destroyed or goes out of scope. It is mainly used for cleaning up or releasing resources
that the object might have acquired during its lifetime, such as closing file handles or
database connections.

Syntax:
<?php
class ClassName {
public function __destruct() {
// Destructor code here
}
}
?>
Example:
<?php
class Database {
public $connection;
// Constructor to initialize the connection
public function __construct($hostname) {
$this->connection = "Connected to database at $hostname";
echo $this->connection;
}

// Destructor to close the connection


public function __destruct() {
echo "\nConnection closed.";
}
}

$db = new Database("localhost");


?>

Output:
Connected to database at localhost
Connection closed.
In this example:
• The constructor establishes a database connection (a simulated message in this
case).
• The destructor is automatically called when the object goes out of scope or when
the script finishes executing.
• It cleans up by outputting a message indicating that the connection is closed.
FORM HANDLING IN PHP

What is Form?
In PHP, a "form" typically refers to an HTML form that is used to collect and submit
user input to a server. HTML forms are a crucial part of web development and are
often used to create interactive web pages that allow users to input data, make
selections, and submit information to the server for processing.

Creating HTML Form:


HTML forms various data can be collected from the user and can be sent directly to
the server through PHP scripting. There are basically two methods for sending data
to the server one is “GET” and the other one is “POST”.
The example below displays a simple HTML form with two input fields and a submit
button:
<html>
<body>
<form action="welcome.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is
sent for processing to a PHP file named "welcome.php". The form data is sent with
the HTTP POST method.
• To display the submitted data you could simply echo all the variables.
The "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Handling HTML Form Data In Php

Simple HTML Form with PHP form handler

The form data is passed to a PHP file named " form handler.php " for processing when
the user fills out the form below and clicks the submit button. The HTTP POST method is
used to send the form data.
<html>
<body>
<form action=" form_handler.php" method="post">
Username: <input type="text" name="name"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>
</body>
</html>
PHP Form handler script “form_handler.php”:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your password is: <?php echo $_POST["email"]; ?>
</body>
</html>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy