You are on page 1of 53

Workshop

OBJECT ORIENTED PROGRAMMING


CONTRIBUTIONS

 Presenters: Fazl K. & Shahid A.


 Organized By: Asad K.

 Lead By: Junaid A.

 Special Thanks: Khurram K. for investing his time,


and some good suggestions.
OBJECT ORIENTED PROGRAMMING

 OOP has been introduced since 40 years. But it


took long to inspire programmers to work in
OOP. OOP is getting for a last 15 years and so.
Programmers are now more and more moving
towards OOP. OOP is the advance tool of
programmer (Design Pattern is more advance
than OOP). There are many other programming
technique but they are not consistent and old
fashion.
PROGRAMMING TECHNIQUES OVERVIEW

 Structure or Sequential Programming.


 Modular or Procedural Programming.

 Object Oriented Programming.

 Design Patterns.
STRUCTURE OR SEQUENTIAL PROGRAMMING

 That is the oldest and most classic way of


programming. In this programming technique the
structure is more obvious, programmer write
his/her code in sequential order. The programmer
starts from the top or line one and keep writing the
code line after line to reach the end or the
program. The program execute in the similar way. It
starts executing from line one, the outcome of the
above line in utilize by below line and it keeps on
executing until it reaches the end. Let’s look let
the advantages of such type of programming
technique.
STRUCTURE PROGRAMMING - ADVANTAGES

 No or little analysis is required.


 No re-engineering or restructuring required.

 Speedy way to start coding.

 Idea for short programs, for example college


assignment.
 Ideal to code program tutorials, the execution is
straight forward.
STRUCTURE PROGRAMMING - DISADVANTAGES

 Very hard to manage.


 Use maximum resources, processing and memory.

 Reusability of code is minimum.

 Buggy, change anywhere in the middle can affect


the below coded lines.
 Maximum chances of wear and tear.

 The worst choice for a large or huge programs or


applications.
MODULAR OR PROCEDURAL PROGRAMMING

 As application grew bigger the structure programming


started being failed. Every time the client wants change
anywhere in the middle, the code following that change
needs to be adjusted as well. So it becomes hard to
manage the code. Now people started talking about the
independent segment of code that do not affect the rest
of code, they started to talking about modularity.
 Functions were defined to achieve this goal. Function
has its own effecting area that is limited to its scope. So
these functions help programmers to achieve the
minimum to hit back by the modifications.
PROCEDURAL PROGRAMMING - ADVANTAGES

 Bugs were reduced.


 Effect on the rest program is minimized.

 Use lesser processing and memory then


structure programming due to stacking.
 Improved reusability of the code.

 The size of the code was reduced.


PROCEDURAL PROGRAMMING - DISADVANTAGES

 RE-engineering and restricting is required time


to time.
 Need to spend time that which part of the code
should be include in which procedure.
 For large applications, it is difficult to draw and
implement the blue print of entire application.
 How these procedure should be structure to
run the application.
OBJECT ORIENTED PROGRAMMING

 It this type of programming technique the entity of business for


converted into classes. These classes define the way to implement
the entities. Classes describe the way to handle objects of the
business entity. This is more natural way of describing entities. Using
these classes you can implement every possible functionality
associated with the entity and every possible property the entity can
hold.
 These entities can be tangible like
 Employees
 Clients
 Cash
 Or can be un tangible
 Transaction
 Accounts
OOP - ADVANTAGES

 More natural way of programming.


 You know in advance how you can handle the
entity, because before creating an object, you
already have implemented implementation and
properties of that entity.
 More reusable.

 In fact classes like Database and Query can be


copy and paste into any other project.
OOP - DISADVANTAGES

 Takes more time in analysis.


 May more re-engineer and more re-
development.
CLASS
 A class is a code template used to generate objects. You
declare a class with the class
 keyword and an arbitrary class name. Class names can be any
combination of numbers and letters,
 although they must not begin with a number. The code
associated with a class must be enclosed within
 braces. Let’s combine these elements to build a class.

class Employee {
// class body
}
SCOPE

 You might have heard about scope, Scope is


the variable or data member boundary in which
it lives. It have influence limited to that
boundary.
 Global Scope

 Function Scope

 Class Scope

 Instance scope
GLOBAL SCOPE

 Global Scope is the main scope of the


application. It is the outer most scope. In other
words if variable doesn’t belong to any other
scope it belongs to global scope. So the
variables declared in this scope lives until the
application is running. And they are washed out
when application stop running.
FUNCTION SCOPE

 When you start working with the variables in


functions, their scope become function scope.
And the existing of these variables last till
function ends, that is either ’RETURN’
statement or body delimiter ‘}’ reached.
 But I am afraid it is not that simple we have
several exceptions
FUNCTION SCOPE - ARGUMENTS
 There are two methods of passing arguments. By value
or By reference.
 By default arguments are passed by value. By value
means when you pass a global
variable value to the function. In this case the value of
this variable is copied to the function. Both the variables
work isolated in their respected scope
 By reference passed arguments gets the reference of
the variable form the other scope. That means change
the variable in either scope will change the value of the
variable at the both end. If you want to pass the
arguments by value, you use ‘&’ with the variable.
FUNCTION SCOPE - GLOBAL

 You can bring the variable your global scope to


function scope, by using ‘global’ or ‘$_GLOBAL’
collection/array
FUNCTION SCOPE - CLASS

 When using function within a class, method,


you can use the class scope data members,
with that are defined with ‘STATIC’ keyword
FUNCTION - INSTANCE

 When using function within a class, you can


use instance data members with ‘$this’
keyword
CLASS SCOPE
 Data member of the class can be accessed with the
reference of the class, either by calling within a class or
from outside the class. These data members, of even
methods, require the class reference to call/use them.
When you are within a class you can call class data
member, you should use ‘self’, If you are outside the
class you should use name of the class. In both cases
you use ‘::’ in between.
 MySQL::connect();
 Self::connect();
 Self::$lastInsertID;
INSTANCE SCOPE
 Well if you want to use the classes, you are not limited
to the class scope only. You can make instances of the
single class. In fact you can make as many instances
as you need of the class.
Class Employee{
// body
}

$fazlK = new Employee(‘Fazl K.’);


$fazlK->department = ‘php’;
Or within a class
$this->deparment = ‘php’;
$fazlK->get_current_projects();
Or within a class
$this-> get_current_projects();
$shahidA = new Employee(‘Shahid A.’);
CLASS SCOPE
 You can define data members and methods with class scope. In that case
you will not require to get into the hustle of creating unnecessary instances.
And unlike the dependency of the instance, you can directly call class
resource from anywhere you like.
 You can access both methods and properties in the context of a class
 rather than that of an object. Such methods and properties are “static” and
must be declared as such by
 using the static keyword.
Class MySQL{
Static $resource;
Static $lastInsertId;
Static function connect(){
Self::$resource =
mysql_connect(DB_HOST, DB_USER, DB_PASS );
}
}
STATIC
 Static methods are functions with class scope. They
cannot access any normal properties in the class,
because these would belong to an object, but they can
access static properties. If you change a static property,
all instances of that class are able to access the new
value.
 Because you access a static element via a class and not
an instance, you do not need a variable that
 references an object. Instead, you use the class name in
conjunction with ‘::’.
 Constant Properties
CONSTANT PROPERTIES
 Some properties should not be changed. The Answer to Life,
the Universe, and Everything is 42, and you
 want it to stay that way. Error and status flags will often be
hard-coded into your classes. Although they
 should be publicly and statically available, client code should
not be able to change them.
 PHP 5 allows us to define constant properties within a class.
Like global constants, class constants
 cannot be changed once they are set. A constant property is
declared with the const keyword. Constants
 are not prefixed with a dollar sign like regular properties. By
convention, they are often named using
 only uppercase characters
CONSTANT PROPERTIES - EXAMPLE
Class MySQL{
Static $resource;
Static $lastInsertId;
const DB_HOST = ‘localhost’;

const DB_USER = ‘root’;


const DB_PASS = ‘’;
Static function connect(){
Self::$resource = mysql_connect(self::DB_HOST, self::DB_USER,
self::DB_PASS );
}
}
INHERITANCE
 Inheritance is the means by which one or more classes
can be derived from a base class.
 A class that inherits from another is said to be a
subclass of it. This relationship is often described in
 terms of parents and children. A child class is derived
from and inherits characteristics from the parent.
 These characteristics consist of both properties and
methods. The child class will typically add new
 functionality to that provided by its parent (also known
as a superclass); for this reason, a child class is
 said to extend its parent.
INHERITANCE - EXAMPLES
Class Employee{

Class HREmployee extends Employee{

Class HRManager extends HREmployee{

Class Developer extends Employee{

}
ABSTRACT CLASSES
 An abstract class cannot be instantiated. Instead it
defines (and, optionally, partially implements)
 the interface for any class that might extend it.
 You define an abstract class with the abstract keyword.
Let us try our abstract class
Abstract class Employee{
}

 Employee is a base class so it makes sense to leave


some of the class implementation to the child class. Let
the child class add some functionality to this class
ABSTRACT CLASS - CONTINUE
Abstract class Employee{
Abstract function get_tasks();
}

 Well to know the task of the employee, you


should first know the position or type of the
employee, we have different tasks for HR
Employee and developer. At this stage we don’t
want to do any stuff right now, we would just
want to force the child classes to implement
this class. ‘Force’
ABSTRACT CLASS - CONTINUES
 we should discuss a few important espect of abstract
here
 Abstract function is the function with no body.
 Any class that includes abstract function must also be
declared abstract.
 You cannot make instance(s) of abstract classes.
 Child class should implement all the abstract function of
the parent abstract class or else child class should also
be declared as an abstract class.
 And if you try to work with them, using any other way you
will end up with an error.
INTERFACES
 While abstract classes let you provide some measure
of implementation, interfaces are pure templates.
 An interface can only define functionality; it can never
implement it. An interface is declared with the
 interface keyword. It can contain properties and
method declarations, but not method bodies.
 Interface Rules {
Function get_leave_quota();
Function get_work_timings();
}
IMPLEMENT THE INTERFACE

 To force programmers to implement coding


standards. We define interface that will force
programmer to implement coding standards.
Abstract Class Employee implement Rules{
}
//You can implement multiple interfaces, like

Abstract class Employee implements Rules,


CodingStandards{

}
FINAL

 Final keyword prevents class or function to


override. Any class declared with final can’t
have a child. And that is also true for function.
Any function declared with final keyword can’t
by override by the the child class function.
Example for a class.
FINAL CLASS
Final class TeamLead extends Developer{
}
//Extending this class will result in error
Class AssociateTeamLead extends TeamLead{
}

//Now you can try something different, that works for you
Class AssociateTeamLead extends Developer {
}
FINAL FUNCTION
Abstract Class Employee implements Rules,
CodingStandards{
Final function set_salary($amount){
}
}
Every employee has salary, what is so special to implement with every user type.
We will be get into trouble If we try something like below
Class Developer extends Employee{
Function set_salary($amount){
}
}
INSTANCE / OBJECT
 If a class is a template for generating objects, it follows
that an object is data that has been structured
 according to the template defined in a class. An object is
said to be an instance of its class. It is of the
 type defined by the class.
 If will not be able to create instance for class Employee
as it is of abstract. So we will try to create instance for
class Developer.
 $fazl = new Developer();
 Let us get into more detail of class Developer, So that
we can explore more
OBJECT INSTANCE – EXAMPLE
Class Developer extends Employee{
Public $name;
Protected $salary;
Protected $department;
Private $tasks;
Function Developer($name=NULL){
If($name!=NULL) $this->name = $name;
}
Implement parent abstract method so that we can create instance for
this class
Function get_tasks(){
}
Function set_tasks(){
}

}
INSTANCE MEMBER VISIBILITY

 That means how can the object members like


methods and data members can be access. In
class we can set the public visibility or make it
private.
PUBLIC
 Any data member that is accessible from outside
the scope of the class. You can create an instance
add start working with these class members. In
the above example ‘$name’ is the example of
public data member. It is save to do something like
this
 $fazlK = new Developer();
 $fazlK->name = ‘Fazl K.’;
 One more example from the above class is
‘function Developer’, as it is not declared private,
so be default it is public.
PRIVATE
 The opposite to the public, the members that can
only be accessed within a class. Calling them
outside the class is prohibited.
 $fazlk->tasks = array(‘MyHSGameFile’=>array((
 ‘create coach panel’,
 ‘create athlete panel’
 ));
 The above code will end up with error. As we are
accessing private ‘tasks’ from outside the class.
PROTECTED
 We have one extreme public, and we have other extreme private. We
also have some compromised solution. We ever we have two choices
in most cases we also have a hybrid choice as well.
 By protecting class members we can extends its visibility to child
classes. You can then override them as well.

 Class AssociateTeamLead extends Developer{


 Function AssociateTeamLead(){
 $this->department = ‘PHP’;
 }
 Function get_department(){
 Return $this->departmemt;
 }
 }
CONSTRUCTOR

 The class member which initialize the class.


Constructor can be define, or if you don’t, class
is initialize without any constructor.
 There are two flavor of constructors. Class
Name and magic function.
CLASS NAME CONSTRUCTOR

 This constructor is defined by naming the


method to the class name, like we did it in the
last class ‘AssociateTeamLead’.
 $asadK = new AssociateTeamLead();

 Echo $asadk->get_department();

 This will echo ‘PHP’, the reason is that


AssociateTeamLead was called on ‘new
AssociateTeamLead();’
MAGIC FUNCTION CONSTRUCTOR
 You can replace the name function constructor with the
method ‘__construct()’, so let us try this constructor.
 Class AssociateTeamLead extends Developer{
 Function __construct(){
 $this->department = ‘PHP’;
 }
 Function get_department(){
 Return $this->departmemt;
 }
 }
IS A RELATIONSHIP

 When a certain type of entity is a sub type of


any existing entity. For example ‘Developer’ IS
A(n) ‘Employee’, and `TeamLead` IS A
‘Developer’.
 These type of relation is implemented in the
parent and child way.
HAS A RELATIONSHIP
 When an entity can’t be a sub type on existing entity, and it actually hold the
other entity. For example, Car is not an Engine, but it actually holds or ‘HAS
A(n)’ engine.
 In our tried example, we would like to introduce a client. Developer ‘HAS A’
client.
 I have omitted the rest of course, just writing the code of our concern here.

 class Developer extends Employee{
 protected $client;
 function set_client(Client $client){
 $this->client = $client;
 }
 }
 Declaring the argument with the type of argument, set client will only accept
the instance of client class.
OBJECT COMPARISON
 Object can be compare but the comparison is an interesting
phenomena. To understand it we need to conduct an example.
 $junaidA = new Developer(‘Junaid A.’);
 $tlJunaid = new Developer(‘Junaid A.’);
 Echo ($junaidA==$tlJunaid) ? ‘Equal’ : ‘Not Equal’;
 You are happy as you get the desired result ‘Equal’. Now let’s make
the check even tighter.
 Echo ($junaidA===$tlJunaid) ? ‘Equal’ : ‘Not Equal’;
 Now you get worried as you get ‘Not Equal’. What is wrong, they both
are instance of same class and holds the same data. But still are not
equal.
 Actually $junaidA and $tlJunaid holds the reference of the instance,
not the complete instance.
OBJECT COMPARASION - EXPLAINATION
 Both object are said to be equal if they points to the
same instance. Confused…
 Let’s watch this in more detail
 $junaidA=$tlJunaid;
 Echo ($junaidA===$tlJunaid) ? ‘Equal’ : ‘Not Equal’;
 You will get ‘Equal’ now. Let us proceed with example.
 $junaidA->name = ‘Junaid Ali’;
 Echo $junaidA;
 Echo $tlJunaid;
OBJECT COMPARISON - EXPLAINATION

Developer Object Developer Object
( (
[name] => Junaid Ali [name] => Junaid Ali
[salary:protected] => [salary:protected] =>
[department:protected] => [department:protected] =>
[tasks:Developer:private] [tasks:Developer:private]
=> =>
[quota:protected] => [quota:protected] =>
[timimgs:protected] => [timimgs:protected] =>
[client:protected] => [client:protected] =>
) )

 By changing the name for ‘$junaidA’, it also has changed the name for ‘$tlJunaid’.
That means that we have two handler for one instance. These two variables have the
reference of same instance.
CLONE
 You might want to copy the reference of an object
and may want not to share the instance between
two variables. So instead of
 $junaidA=$tlJunaid;
 Try This
 $junaidA= clone $tlJunaid;
 $junaidA->name = ‘Junaid Ali’;
 Echo $junaidA;
 Echo $tlJunaid;
CLONE CONTINUES
Developer Object( [name] => Junaid Ali Developer Object( [name] => Junaid A.
[salary:protected] => [salary:protected] =>
[department:protected] => [department:protected] =>
[tasks:Developer:private] => [tasks:Developer:private] =>
[quota:protected] => [timimgs:protected] [quota:protected] => [timimgs:protected]
=> [client:protected] => ) => [client:protected] => )

You might also like