Day 15: Object Oriented Programming in PHP

Introduction to OOPS

Php5 released in 2004 with OOP features like in C# and java. It was the big change in PHP and now we can code with classes and objects in PHP.

In next few days, I will guide you how to work with OOP in PHP.

let’s take a look terms related to Object Oriented Programming :

Class: is a collection of member variables and functions.

Object: is a instance of class, we can create multiple instance of a class.

Member Variable: variable defined in class are called member variable of that class. Variable holds data that will be invisible to the outside of the class.

Member Function: function defined in class are called member function and use to access data.

Inheritance: Inheritance is a mechanism wherein a new class is derived from an existing class.

Polymorphism: when same function used for different purpose it’s called Polymorphism. Like:- function name will remain same name but it take different number of arguments and can do different tasks.

Data Abstraction:Data abstraction represent to, providing only essential information to the outside world and hiding their background details.

Encapsulation: Encapsulation is the process of packing of data and functions into a single component.

Constructor: is a special type of function which will be called automatically whenever there is an object formation of a class.

Destructors: is a special type of function which will be called automatically whenever an object is deleted.

Program 42: Defining class and function in PHP

<?php
class myClass {
function display() {
echo “i am in display”;
}
}
$obj = new myClass();
$obj->display();
?>

Explanation: new is the keyword in above code. new keyword is use to create object of the class. $obj-> is used to call the function of the class.

Program 43: Constructor function

<?php
class myClass {
function __construct(){
echo “i am in constructor.”;
}
}
$obj = new myClass();
?>

As defined above Constructor is a special type of function which will be called automatically whenever there is an object formation of a class. Like in above example, we have created object of the class and constructor called automatically.

Program 44: Destructor function

<?php
class myClass {
function __destruct(){
echo “i am in destructor.”;
}
}
$obj = new myClass();
?>

As a constructor function we can also define a destructor function using function __destruct(). We can release all the resources with-in a destructor.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.