Unit-04 Php Class and Object
Unit-04 Php Class and Object
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 .
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
{(
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
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.
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.”
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.";
}
}
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";
}
}
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.
CONSTRUCTOR:
Example:
<?php
class Car {
public $model;
public $color;
// Constructor
public function __construct($model, $color)
{
$this->model = $model;
$this->color = $color;
}
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;
}
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.
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>