OOP (Object Oriented Programming)
- Concept of OOP
Object oriented programming is nothing but a technique to design your application. Application could be any type like it could be web based application, windows based application. OOP is a design concept. In object oriented programming, everything will be around the objects and class. By using OOP you can create modular web application. By using OOP we can perform any activity in the object model structure. There are many benefit of using oop over the parallel or procedural programming.
· Object
Any thing is the world is an object. Look around and you can find lots of object. Your laptop, pc, car every thing is an object. In this world every object has two thing properties and behaviors. Your car has property (color, brand name) and behavior(it can go forward and backward). If you are able to find properties and behaviors of real object. Then it will be very easy for you to work with Object Oriented Programming.
The object in programming is similar to real word object. Every programming object has some properties and behaviors. For example, if you have an object for interest calculator then it has property interest rate and capital and behavior simple interest calculation and compound interest calculation. Interest calculator has some property and method from calculator object like addition, multiplication etc.
· Class
The class is something which defines your object. For example, your class is Car. And your Honda car is object of car class. Like object explanation, here we will take an example of the real word and then we will move further in programming definition.
Blueprint of the object is class. The class represents all properties and behaviors of the object. For example, your car class will define that car should have color, the number of doors and your car which is an object will have color green and 2 doors. Your car is an object of a class car. Or in terms of programming, we can say your car object is an instance of the car class. So structural representation (blueprint) of your object is class.
Now let us take an example of the programming. Your interest calculator object is an instance of class interest calculator. Interest calculator class defines properties like capital, rate, and behavior like simple interest calculation and compound interest calculation.
Now in your object when interest calculation behavior will be applied it will take your rate of interest and capital and provide you the result.
· Constructor
When you create a new object, it is useful to initialize its properties e.g., for the bank account object you can set its initial balance to a specific amount. PHP provides you with a special method to help initialize object’s properties called constructor.
To add a constructor to a class, you simply add a special method with the name __construct(). Whenever you create a new object, PHP searches for this method and calls it automatically.
The following example adds a constructor to the BankAccount class that initializes account number and an initial amount of money:
Example :
To add a constructor to a class, you simply add a special method with the name __construct(). Whenever you create a new object, PHP searches for this method and calls it automatically.
The following example adds a constructor to the BankAccount class that initializes account number and an initial amount of money:
Example :
class BankAccount{
private $accountNumber;
private $totalBalance;
public function __construct($accountNo, $initialAmount){
$this->accountNumber = $accountNo;
$this->totalBalance = $initialAmount;
}
}
Now you can create a new bank account object with an account number and initial amount as follows:
$account = new BankAccount('1243845355',2000);
· constructor overloading
Constructor overloading allows you to create multiple constructors with the same name __construct() but different parameters. Constructor overloading enables you to initialize object’s properties in various ways. The following example demonstrates the idea of constructor overloading:
Example :
public function __construct(){
}
public function __construct($accountNo){
$this->accountNumber = $accountNo;
}
public function __construct($accountNo, $initialAmount){
$this->accountNumber = $accountNo;
$this->totalBalance = $initialAmount;
}
We have three constructors:
- The first constructor is empty, it does nothing.
- The second one only initializes account number.
- The third one initializes both account number and initial amount.
PHP have not yet supported constructor overloading, Oops. Fortunately, you can achieve the same constructor overloading effect by using several PHP functions.
· Destructor
PHP destructor allows you to clean up resources before PHP releases the object from the memory. For example, you may create a file handle in the constructor and you close it in the destructor.
To add a destructor to a class, you just simply add a special method called __destruct() as follows:
To add a destructor to a class, you just simply add a special method called __destruct() as follows:
public function __destruct(){
// clean up resources here
}
There are some important notes regarding the destructor:
There are some important notes regarding the destructor:
- Unlike a constructor, a destructor cannot accept any argument.
- Object’s destructor is called before the object is deleted. It happens when there is no reference to the object or when the execution of the script is stopped by the
exit()
function.
The following simple FileUtil class demonstrates how to use the destructor to close a file handle.
<?php
class abc
{
function __construct()
{
echo "this is a constructor";
}
function __destruct()
{
echo "this is a destruct";
}
}
$obj=new abc;
?>
In this tutorial, we have introduced PHP constructor and destructor to help you initialize object’s properties and clean up resources before the object is deleted.
· The concept of inheritance
Inheritance is a process of creating a new class from the existing class. There is a two classOldclass
New class
Old class is also refered as a Super, Base, Parent
New class is also refered as a Sub, Derived,Child
Types of inheritance
1) Single- One super one child class
2) Multiple(Not supported)-Multiple super class and one sub
3)Multilevel- One sub class become super class of other
4)Hirratchical-One Super class and multiple sub
5) Hybrid-Combination of any two or more inheritance
1) Single- One super one child class
2) Multiple(Not supported)-Multiple super class and one sub
3)Multilevel- One sub class become super class of other
4)Hirratchical-One Super class and multiple sub
5) Hybrid-Combination of any two or more inheritance
When referencing these items from outside the class definition, use the name of the class.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
Example #1 :: from outside the class definition<?php
class MyClass {
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0
echo MyClass::CONST_VALUE;
?>
Two special keywords self and parent are used to access members or methods from inside the class definition.
Example #2 :: from inside the class definition<?php
class OtherClass extends MyClass
{
public static $my_static = 'static var';
public static function doubleColon() {
echo parent::CONST_VALUE . "\n";
echo self::$my_static . "\n";
}
}
$classname = 'OtherClass';
echo $classname::doubleColon(); // As of PHP 5.3.0
OtherClass::doubleColon();
?>
When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.
Example #3 Calling a parent's method<?php
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()\n";
}
}
class OtherClass extends MyClass
{
// Override parent's definition
public function myFunc()
{
// But still call the parent function
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}
$class = new OtherClass();
$class->myFunc();
?>
· Autoloading Class Files
how to organize your class files and load them automatically using PHP __autoload() function.
It is good practice to keep each PHP class in a separated file and all class files in a folder named classes. In addition, the name of the class should be used to name the file for example if you have a Person class, the file name should be person.php.
Before using a class you need to load it in your script file using PHP include file function such as require_once() as follows:
require_once("classes/bankaccount.php");
$account = new BankAccount();
When the number of classes grows, it is quite tedious to call require_once() function everywhere you use the classes. Fortunately, PHP provides a mechanism that allows you to load class files automatically whenever you try to create an object from a non-existent class in the context of the current script file.
PHP will call __autoload() function automatically whenever you create an object from a non-existent class. To load class files automatically, you need to implement the __autoload() function somewhere in your web application as follows:
It is good practice to keep each PHP class in a separated file and all class files in a folder named classes. In addition, the name of the class should be used to name the file for example if you have a Person class, the file name should be person.php.
Before using a class you need to load it in your script file using PHP include file function such as require_once() as follows:
require_once("classes/bankaccount.php");
$account = new BankAccount();
When the number of classes grows, it is quite tedious to call require_once() function everywhere you use the classes. Fortunately, PHP provides a mechanism that allows you to load class files automatically whenever you try to create an object from a non-existent class in the context of the current script file.
PHP will call __autoload() function automatically whenever you create an object from a non-existent class. To load class files automatically, you need to implement the __autoload() function somewhere in your web application as follows:
<?php
spl_autoload_register(function($class_nm)
{
include $class_nm.'.php';
}
);
$obj=new MYCLASS1;
$obj1=new MYCLASS2;
{
include $class_nm.'.php';
}
);
$obj=new MYCLASS1;
$obj1=new MYCLASS2;
Whenever you create an object from a non-existent class, PHP looks into the ./classes folder and load the corresponding class file using the require_once() function.
From now on, you don’t have to call require_once() function every time you use the class, which is very useful.
Notice that if PHP cannot find the __autoload() function or if the __autoload() function failed to load the class files, you will get an error message.
· Class constants
A constant is, just like the name implies, a variable that can never be changed. When you declare a constant, you assign a value to it, and after that, the value will never change. Normally, simple variables are just easier to use, but in certain cases constants are preferable, for instance to signal to other programmers (or your self, in case you forget) that this specific value should not be changed during runtime.
Class constants are just like regular constants, except for the fact that they are declared on a class and therefore also accessed through this specific class. Just like with static members, you use the double-colon operator to access a class constant. Here is a basic example:
<?php
class User
{
const DefaultUsername = "John Doe";
}
const MinimumPasswordLength = 6;
}
echo "The default username is " . User::DefaultUsername;
echo "The minimum password length is " . User::MinimumPasswordLength;
?>
As you can see, it's much like declaring variables, except there is no access modifier - a constant is always publically available. As required, we immediately assign a value to the constants, which will then stay the same all through execution of the script. To use the constant, we write the name of the class, followed by the double-colon operator and then the name of the constant. That's really all there is to it.
No comments:
Post a Comment