SHRI PAL SINGH

An Enterpreneur With Kind Heart

Blog

Use of OOPS in PHP – Basic Tips

Object Oriented:
Definition: It is a technique to design the project as a set of logical object communicating to each other to full fill certain goal of user. It is a programming paradigm where we emphasis on data and write methods to manipulate the data or properties of object.

Features and concepts
Abstraction:
This is a way that represents essential characteristics of an object that differentiate it from other object and hiding the detailed characteristics.

Encapsulation
Encapsulation is a process to wrapping the data and function in single unit. Thus it is the way to get the abstraction because details are encapsulated in a unit.

Inheritance
Mechanism to extend the functionlists of one object to another project. This feature helps us to reuse properties and function of one class into other class.

Polymorphism
This feature allows us to assign the multiple role to single object. An object or function exists in many forms and play different role in execution.

Implementations
Class Defines the characteristics of the Object.

class MyClass {
var $author="Abc";
public function sayHello(){
echo "Hello User";
}
}

Object
An Instance of a Class. It is logical module created form class having state and behavior. Properties of object specifies state and method/function depicts behavior.

$m = new MyClass();
$m->sayHello();

If you do as following
$n=$m;
then same object is being referenced from $n, but no new object’s been created.

Property
An Object characteristic, such as author in MyClass
Method
An Object capability, such as sayHello.
It is defined / declared as function in Object.
Parametrized method:
method that can take arguments/values to be manipulated or used by the method.
this keyword :
Is is used to refer the self object. The this pointer points the object in which it resides.
It is used to differentiate the local and instance members. Like see the $name variable in following example.

class MyClass{
var $name=”Abc”;
public function sayHello($name){
echo “Hello”.$this->name;
}
}
$m = new MyClass();
$m->sayHello(“Deepak”);

Here, the $name parameter (local variable) is sayHello() method is not being used, because
$name is being referred through this so it is the instance variable instead of local variable.

Returning value from method/function:
This technique is used mostly to get work done by method and receive the result on same place from where method is invoked.

class MyClass{
var $name=”Abc”;
public function sayHello($name){
echo “Hello”.$this->name;
}
}
$m = new MyClass();
$msg=$m->sayHello(“Deepak”);
echo $msg;

static members:
The members of class those are declared as static does not become part of an object. Static members are located with the class name and they are shared among the objects.
PHP interpreter creates only single copy of static members throughout the web application.

self:: is used to access them within class
class name is used to access them outside of containing class

class MyClass{
var $name=”Abc”;
public function sayHello($name){
echo “Hello”.$this->name;
}
}
$m = new MyClass();
$msg=$m->sayHello(“Deepak”);
echo $msg;
echo ‘Again Hello’.MyClass::$name;

Method overloading in PHP :
Method overloading is the property of method to perform different activities based on argument passed to it. But in PHP, method overload is not done by creating multiple method with single name and using different parameter types and different parameters count.
PHP support this feature sing _call magic method as depicted bellow.

class MyClass{
public function __call($name,$parameter){
if($name==”add”){
$count = count($parameter);
switch ($count){
case “1”:echo $parameter[0];
break;
case “2”:echo $parameter[0]+$parameter[1];
break;
case “3”:echo $parameter[0]+$parameter[1]+$parameter[2];
break;
default:echo ‘No parameter matched’;
}
}
}
}
$m = new MyClass();
$m = add(1,3);
$m = add(1,3);
$m = add(1,3);

Constructor
Its a method like block of code that is executed automatically just after object created.
It execute only once when object of the class is created. But execute every time you create the object of the class in which it is defined.
It does not have own name and always created using _construct() name.

Using type Hints
This feature used to validate the arguments to be passed or used in functions. Now functions can declare the type for its parameters. When function is executed, PHP interpreter checks whether or not the arguments are of the specified type. The run-time error is raised if arguments do not match with expected type and execution is halted.

Inheritance
It is mechanism to extend functionality and properties of one class to another class. It is used to extend the functionality of existing Object in other-way.

Invoking Constructor of Parent Class
If you define constructor in sub class, you need to pass required arguments to the constructor of parent class. To refer a member of parent class, php provides parent keyword.

Method Overriding
If any method of Parent class is redefined by child class, its called overriding of that method.

Access Specifiers: Public, Private, and Protected

  • Public properties and methods can be accessed from any context or name space
  • A private method or property can only be accessed from within the enclosing class. Even subclasses have no access.
  • A protected method or property can only be accessed from within either the enclosing class or
    from a subclass. No external code is granted access.

DTO or BO or Entity Pattern class: i.e. Accessor or getters/setters methods
Some time we need to avoid direct access to the variables (Properties) of a classes. Instead of this, we create getter and setter methods for each property.
Like if we have a property $name, we keep it private and create two methods that are getName() and setName($name).
To set values we can use parametrized constructor.

Static Members
Any method or property declared with static keyword is referred as static member of class. Static member are accessed from class rather then object.
Static members will not be associated with the Object created from a class in which static member are declared.
There will be single copy of a static member through out the context of an application. So you can use static member to share values among different object within the particular project.
Static members are accessed without creating the object of the class they are part of. They are accessed with the class name and within class you can use self keyword.

Abstract Class
Any class having any declared or abstract methods must be declared as abstract as abstract class. Sometime class does not have any abstract method but they may be declared abstract.
We cannot instantiate or cannot create an object of an abstract class.
Abstract classes are inherited or extended only.
Any method declared abstract in abstract class is supposed to be implemented by child class otherwise child classes also declared as abstract.

abstract class Printer{
abstract function startPrinting($data);
function printerName(){
echo “Hp laser printer”;
}
}
class LaserPrinter extends Printer{
public function startPrinting($data){
echo “Laser print :”.$data;
}
}
$p1 = new LaserPrinter();
$p->startPrinting(“Testing printer”);

Interface
Interfaces are used to create the template to be implemented by other classes. Interface can declare methods but they cannot implement them. They define the predefined behavior of object those will be created form the class that will implement it.
Interface depicts the behavior of an object to the programmer that how to use the object and facilities object will provide.
Interface set the protocols between development team to use semantic approach in coding and to meet some level of commonality in coding.

interface Printer{
abstract function startPrinting($data);
}
class LaserPrinter implements Printer{
public function startPrinting($data){
echo “Laser print :”.$data;
}
}
$p1 = new LaserPrinter();
$p->startPrinting(“Testing printer”);

Constant
To declare any variable as a constant, php provide const keyword and do not use $ before variable name. And as per naming convention, constant variable name is taken in Uppercase.

const PI=3.14;

Polymorphism implementation
Here, we are implementing working of printNow() function in polymorphic way. This function just change the output as we change the Printer Object.
So changing the behavior of any object (like Computer in this example) allows that object to play multiple roles without changing any coding line of that object.

Code Re-factored during training session

interface Sim {
public function call($qqweq);
}
class Mobile{
private serviceProvider;
function setProvider(Sim $serviceProvider){
$this->serviceProvider->call($phone);
}
}
class Airtel implements Sim{
function call($phone){
echo “Airtel: Hello to”.$phone;
}
}
class Idea implements Sim{
function call($phone){
echo “Idea: Hello to”.$phone;
}
}
class Mem{
function sdfsf($phone){
echo “MySim: Hello to”.$phone;
}
}
$mobile = new Mobile();
$mobile->setProvider(new Idea());

$mobile2 = new Mobile();
$mobile->setProvider(new Airtel());
$mobile->makeCall(324324);
$mobile->makeCall(324324);

Other topics:
Final Classes and Methods Final classes cannot be inherited Final methods cannot be overridden

Object Closing
PHP provide
Clone method for cloning the created object. Using the clone, we can create an object by copying already created object.
It copies complete state of object.
Implementing Clone method:

class User{
private $name;
private $email;
private $id;
function construct ($name,$email){
$this->name = $name;
$this->email =$email;
}
function setId($id){
$this->id = $id;
}
clone(){
function
$this->id = 0
}

}

using clone method
$user = new User(“bob”,”user@gmail.com”);
$user->setId(343);
$user2 = clone $user;

toString() method (PHP5.2)

class User{
private $name;
private $email;
private $id;
function construct ($name,$email){
$this->name = $name;
$this->email =$email;
}
function setId($id){
$this->id = $id;
}
public toString(){
return $this->name.”,”.$this->email;
}
}

$user = new User(“abc”,”abc@gmail.com”);
print $user;

Error Handling
Sometime abnormal execution happens in your project or in server. In this situation, error logs are generated to find the root cause for the error. Apache server capability to capture the errors at various level and in various part of your application. But there are some limitations for handling error at each execution of your code. Like, Apache cannot log error messages if some one enters wrong password in user log-in form. Because this is the functionality of you application.

SHRI

Leave a Reply

Be the First to Comment!

Notify of
avatar
497

wpDiscuz