SlideShare a Scribd company logo
OBJECT ORIENTED PROGRAMMING USING PHP
1
Contents
• OOP Basic
• Classes and Objects
• Methods and Properties
• PhpDocumentor / DocBlock
• Internal Reference and constant
• Member Access Control
• Copying and Cloning Object
• Single Responsibility Principle (SRP)
• Magic Methods(constructor/destructor)
• Inheritance and Protected Scope
• Overriding Parent Method(parent::)
• Abstraction (Abstract Class /Interfaces )
• Method Overloading
• Traits
• Static Methods and Properties
• Autoloading Through SPL
2• Working with namespace
• Defining Namespace
• Using namespace
• Autoloading With PSR-0 Standard
• Dependency Injection
• Getter Setter
-------------------------------------------------------
----------
• Exception Handling
• try, catch, thow new , getMessage
• Exception Classes
• Using mysqli (mysql Improved) for DB
• CRUD in OOP Way
• Class/Library/Framework
• Using composer to download library
For PHP Libs : www.packgist.org
• Using Some Libraries
What is OOP Programming? 3
 Object-oriented programming (OOP) is a programming paradigm(Model,
Pattern) based on the concept of “objects", which are data structures that contain data,
in the form of fields, often known as `attributes` and code, in the form of procedures
or function, often known as methods.
 Historically, a program has been viewed as a logical procedure that takes input data,
processes it, and produces output data.
 Object-oriented programming takes the view that what we really care about are the
objects .
 Examples of objects range from human beings (described by name, address, and so
forth) to buildings and floors (whose properties can be described and managed) down
to the little controls on a computer (such as buttons and scroll bars).
Contd... 4
 The first step in OOP is to identify all the objects the programmer wants to manipulate
and how they relate to each other, an exercise often known as data modeling. Once an
object has been identified, it is generalized as a class of objects which defines the kind of
data it contains and any logic sequences that can manipulate it. Each distinct logic
sequence is known as a method.
 Simula was the first object-oriented programming language. Java, Python, C++, C#
.NET and Ruby are the most popular OOP languages today.
 The Java programming language is designed especially for use in distributed applications
on corporate networks and the Internet.
 Ruby and PHP is used in many Web applications and Web Services.
 Curl, Smalltalk, Delphi and Eiffel are also examples of object-oriented programming
languages.
Contd... 5
 In order to manage the classes of a software system, and to reduce the complexity, system
designers use several techniques, which can be grouped under four main concepts named as :-
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism.
These concepts are the four main gods of OOP world and in software term, they are called
four main Object Oriented Programming (OOP) Concepts.
Benefits of OOP 6
The concepts and rules used in object-oriented programming provide these important benefits:
 The concept of a data class makes it possible to define subclasses of data objects that share
some or all of the main class characteristics. Called inheritance, this property of OOP forces a
more thorough data analysis, reduces development time, and ensures more accurate coding.
 Since a class defines only the data it needs to be concerned with, when an instance of that
class (an object) is run, the code will not be able to accidentally access other program data.
This characteristic of data hiding provides greater system security and avoids
unintended data corruption.
Contd... 7
 The definition of a class is reusable not only by the program for which it is
initially created but also by other object-oriented programs (and, for this
reason, can be more easily distributed for use in networks).
 The concept of data classes allows a programmer to create any new data
type that is not already defined in the language itself.
What is a Class? 8
 A class is simply a representation of a type of object.
 It is the blueprint, or plan, or template, that describes the details of
an object.
 Class is composed of three things: A name, attributes or property, and
operations or method.
What is an Object? 9
 An object can be considered a "thing" that can perform a set
of related activities. The set of activities that the object performs defines
the object's behavior. For example, the Hand (object) can grip
something, or a Student(object) can give their name or address.
 In pure OOP terms an object is an instance of a class.
 For example, the TextBox control, you always used, is made out of
the TextBox class, which defines its appearance and capabilities. Each time
you drag a TextBox control, you are actually creating a new instance of
the TextBox class.
Component-based SW engineering 10
 Component-based software engineering (CBSE) (also known
as component-based development (CBD)) is a branch of software
engineering that emphasizes the separation of concern in respect of the
wide-ranging functionality available throughout a given software system.
 It is a reuse-based approach to defining, implementing and composing
loosely coupled independent components into systems.
 All system processes are placed into separate components so that all of
the data and functions inside each component are semantically related
(just as with the contents of classes). Because of this principle, it is often
said that components are modular and cohesive.
Contd... 11
Contd... 12
A simple example of several software components - pictured within a hypothetical
holiday-reservation system
Defining a Class 13
 Basic class definitions begin with the keyword class, followed by a class
name, followed by a pair of curly braces which enclose the definitions of
the properties and methods belonging to the class.
<?php
class SimpleClass
{
// declare members of class
}
Defining a Class Properties 14
 Class member variables are called "properties".
 You may also see them referred to using other terms such as "attributes"
or "fields“
 Syntax : <access type> $variable_name
<?php
class SimpleClass
{
public $name = “NIIT” // name property
}
Defining a Class Constant 15
 Defining constants differ from normal variables in that you don't use
the $ symbol to declare or use them.
 To get constant value we use self keyword instead of $this
 Always declare constant name in UPPERCASE
<?php
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "n";
}
}
Defining a Class Methods 16
Function inside a class is called as method.
E.g.
<?php
class SimpleClass
{
public function sayHello() // public method
{
return “Hello!!!”;
}
}
Accessing Object Members 17
 We can access object members by using -> operator;
class CollegeInfo
{
public $name = “NIIT”; // public property
public function getCenter() // public method
{
return “Kathmandu”;
}
}
//Creating Object
$niit = new CollegeInfo(); // () is optional when constructor is not defined
echo $niit->name // don’t use $ sign before property name
echo $niit->getCenter(); // accessing method
The $this Attribute 18
 $this attribute is a self referencing object of a class.
 We can access properties and method inside the method by using $this
attribute
e.g.
<?php
class StudentInfo
{
private $studentName = “Michio Kaku”;
public function getStudentName()
{
// getting $studentName using $this attr
return $this->studentName;
}
}
What is Encapsulation? 19
 Encapsulation is one of the four fundamentals of OOP
 A language mechanism for restricting access to some of the object’s
components
 Encapsulation refers to the bundling of data with the methods that operate
on that data.
 Encapsulation is used to hide the values or state of a structured data
object inside a class, preventing unauthorized parties' direct access to
them.
 Publicly accessible methods are generally provided in the class (so-
called getters and setters) to access the values, and other client classes call
these methods to retrieve and modify the values within the object. Also
you can specify Get access or Set access only.
 Encapsulation is also known as Information Hiding
Specifying Visibility Scope 20
 We can perform encapsulation by using visibility scope
 In php there are three types of visibility scopes:
1) public
2) private
3) protected
 public :
When a class member is defined as public that member can be access any where
outside the class.
 private :
When a class member is defined as private that member cannot be access outside the
class
 protected :
When a class member is defined as protected it can only be inside the class
and can access by base class in Inheritance
Constructor 21
 Constructor is a type of method inside a class which gets automatically invoked on every
instantiation of class.
 To define constructor in php name a function __construct.
 Never make constructor private, because you cannot instantiate that class if you make class
constructor private make it always public
<?php
class MyClass
{
public function __construct()
{
// statement here will automatically executed when this class instantiates
}
}
Destructor 22
 Destructor is a type of method inside a class which gets automatically invoked just before
destruction of the object.
 To define destructor in php name a function __destruct
 <?php
class MyClass
{
public function __destruct()
{
// statement here will automatically executed while destroying the class
}
}
PHP Magic Methods 23
 PHP method that start with a double underscore “__” are called magic methods in
PHP.
 They are functions/methods that are always defined inside classes, and are not stand-alone
(outside of classes) functions.
 The magic functions available in PHP are:
__construct(), __destruct(), __toString(), __invoke(), __call(), __callStatic(), __get(), __set(),
__isset(), __unset(), __sleep(), __wakeup(), __set_state(), __clone(), and __autoload().
Why are they called magic functions?
This is why they are called ‘magic’ functions – because they are never directly called, and they
allow the programmer to do some pretty powerful things.
The programmer must actually write the code that defines what the magic function will do. But,
magic functions will never directly be called by the programmer – actually, PHP will call the
function ‘behind the scenes’.
Why use magic method? 24
 To trigger some custom behavior while
 attempt to call not defined methods
 attempt to use object as string
 etc.
 Why not magic method?
 3-20 times slower method call
 IDE warning
Static Members 25
 Declaring class properties or methods as static makes them accessible
without needing an instantiation of the class.
 We can’t call not static member inside static method.
 Static members cannot be accessed through the object using the arrow operator ->
we have to use scope resolution operator ‘::’ to access static members.
Static Property 26
 To define static property we have to use static keyword between access control
and variable name
<?php
class MyClass
{
public static $name = “NIIT”; //static property
}
echo MyClass::$name;
Static Method 27
 To define static member we have to use static keyword between access control and
function keyword
<?php
class MyClass
{
public static function sayHello() // static method
{
return “Hello!!!”;
}
}
echo MyClass::sayHello();
What is Inheritance? 28
 Inheritance is a one of four fundamental principle oop.
 The ability of a new class to be created, from an existing class by extending it,
is called inheritance.
 Doing this allows you to efficiently reuse the code found in your base class.
 In MVC we creates MODEL by Inheriting Model abstract class and Controller
by inheriting Controller abstract class
E.g.1 E.g.2
class HomeController extends Controller { }
we can create as many as controllers by
extending Controller class
Implementing Inheritance 29
 We can inherit class by using extends keyword.
class BaseClass
{
protected $name = “NIIT”;
}
class DerivedClass extends BaseClass // Inheriting BaseClass
{
public function getName()
{
return $this->name;
}
}
$obj = new DerivedClass();
echo $obj->getName();
What is Abstraction? 30
 Abstraction is an emphasis on the idea, qualities and properties rather than
the particulars (a suppression of detail).
 The importance of abstraction is derived from its ability to hide irrelevant
details.
 In case of MVC we creates model by extending / inheriting Model abstract
class. So get functions like where, save, findById etc. which is not declared
in our derived model. That is all suppressed or defined in Model abstract
class.
 Commonly abstraction is performed by extending abstract class and
implementing interfaces.
Abstract Methods and Classes 31
 An abstract class is a type of class that cannot be instantiated, but they can
be subclassed.
 An abstract class is declared using abstract keyword before class
abstract class MyAbstractClass
{
// abstract class members
}
 An abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon) like this:
abstract function moveTo($offsetX, $offsetY);
Contd...
 If a class includes abstract methods, then the class itself must be
declared abstract, as in :
abstract class GraphicObject
{
//declare properties
//declare non-abstract method
abstract function draw();
}
 When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class. However, if it
does not, then the subclass must also be declared abstract
32
Interfaces
 The term interface is often used to define an abstract type that contains no
data or code, but defines behaviors as method signatures
 An interface is a description of the actions that an object can do
 An interface is a programming structure/syntax that allows the computer to enforce
certain properties on an object (class).
 An interface is a shared boundary across which two separate components of a
computer system exchange information.
 Method defined in an interface contains no code and thus cannot itself be called; it
must be implemented by class code to be run when it is invoked.
33
Declaring & Implementing Interface
 <?php
interface IHand
{
public function moveUp($upheight);
public function moveDown($downHeight);
}
class Hand implements IHand
{
public function moveUp($upHeight) {
//move up code
}
public function moveDown($downHeight) {
//move down code
}
}
34
Difference Between An Interface and An Abstract Class
 Interface definition begins with a keyword interface so it is of type interface
 Abstract classes are declared with the abstract keyword so it is of type class
 Interface has no implementation, but they have to be implemented.
 Abstract class’s methods can have implementations and they have to be
extended.
 Interfaces can only have method declaration (public and abstract) and properties
(public static)
 Abstract class’s methods can’t have implementation only when declared abstract.
 Abstract class can implement more than one interfaces, but can inherit only one
class
 Abstract class can be used to provide some default behavior for a base class.
35
Contd...
 Interface makes implementation interchangeable
 Interface increase security by hiding the implementation
 Abstract class can be used when implementing framework
 Abstract classes are an excellent way to create planned inheritance hierarchies
and also to use as non-leaf classes in class hierarchies.
For example, if you have an application framework, an abstract class can be used to
provide the default implementation of the services and all mandatory modules such
as event logging and message handling etc.
This approach allows the developers to develop the application within the guided
help provided by the framework.
36
What is Polymorphism? 37
 Polymorphisms is a generic term that means 'many shapes'.
 More precisely Polymorphisms means the ability to request that the same
operations be performed by a wide range of different types of things.
What is Method Overloading? 38
 Method overloading is the ability to define several methods all with the same
name.
 E.g.
class DB
{
public function connect(){ // connection code }
public function connect($server, $uid, $pass, $db) { // connection code }
}
Traits 39
 Traits are used to solve a problem in OOP languages such as PHP that only allow
for single inheritance
 It is new in PHP 5.4
<?php
trait tSomeTrait
{
// Attributes
function someFunction() {
// Do whatever.
}
}
Contd… 40
 We can add tratis to class via the use keyword inside the class definition
<?php
class SomeClass {
use tSomeTrait;
// Rest of members.
}
 Now, when you createan object of type SomeClass, that object has a
someFunction() method:
$obj = new SomeClass();
$obj->someFunction();
Type Hinting 41
 Type hinting is the programming act of indicating what type of value is expected. For
example, what type
 Type hinting doesn’t play much of a role in procedural PHP code because you cannot
hint simple types (e.g ., integers or strings). of value a function expects to receive for a
parameter.
Ad

More Related Content

What's hot (20)

09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
Denis Ristic
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
 
Php Oop
Php OopPhp Oop
Php Oop
mussawir20
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
Rajesh S
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
Mindfire Solutions
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
Nyros Technologies
 
Intro to OOP and new features in PHP 5.3
Intro to OOP and new features in PHP 5.3Intro to OOP and new features in PHP 5.3
Intro to OOP and new features in PHP 5.3
Adam Culp
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
Alena Holligan
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
Mutinda Boniface
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
Dot Com Infoway - Custom Software, Mobile, Web Application Development and Digital Marketing Company
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
indiangarg
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
Hitesh-Java
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
tutorialsruby
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
Denis Ristic
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
Rajesh S
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
Nyros Technologies
 
Intro to OOP and new features in PHP 5.3
Intro to OOP and new features in PHP 5.3Intro to OOP and new features in PHP 5.3
Intro to OOP and new features in PHP 5.3
Adam Culp
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
Alena Holligan
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
indiangarg
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
tutorialsruby
 

Similar to Php oop (1) (20)

My c++
My c++My c++
My c++
snathick
 
OOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHatOOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
SadiqullahGhani1
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
Army Public School and College -Faisal
 
The smartpath information systems c plus plus
The smartpath information systems  c plus plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
Abap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialsAbap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorials
cesarmendez78
 
Oops
OopsOops
Oops
Sankar Balasubramanian
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
Questpond
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
mrxyz19
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
Inocentshuja Ahmad
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
vamshimahi
 
OOPS 46 slide Python concepts .pptx
OOPS 46 slide Python concepts       .pptxOOPS 46 slide Python concepts       .pptx
OOPS 46 slide Python concepts .pptx
mrsam3062
 
Only oop
Only oopOnly oop
Only oop
anitarooge
 
Lab 4 (1).pdf
Lab 4 (1).pdfLab 4 (1).pdf
Lab 4 (1).pdf
MohammedAlobaidy16
 
Oops
OopsOops
Oops
Jaya Kumari
 
C#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersC#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developers
Sanjaya Prakash Pradhan
 
Ad

Recently uploaded (20)

Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Ad

Php oop (1)

  • 2. Contents • OOP Basic • Classes and Objects • Methods and Properties • PhpDocumentor / DocBlock • Internal Reference and constant • Member Access Control • Copying and Cloning Object • Single Responsibility Principle (SRP) • Magic Methods(constructor/destructor) • Inheritance and Protected Scope • Overriding Parent Method(parent::) • Abstraction (Abstract Class /Interfaces ) • Method Overloading • Traits • Static Methods and Properties • Autoloading Through SPL 2• Working with namespace • Defining Namespace • Using namespace • Autoloading With PSR-0 Standard • Dependency Injection • Getter Setter ------------------------------------------------------- ---------- • Exception Handling • try, catch, thow new , getMessage • Exception Classes • Using mysqli (mysql Improved) for DB • CRUD in OOP Way • Class/Library/Framework • Using composer to download library For PHP Libs : www.packgist.org • Using Some Libraries
  • 3. What is OOP Programming? 3  Object-oriented programming (OOP) is a programming paradigm(Model, Pattern) based on the concept of “objects", which are data structures that contain data, in the form of fields, often known as `attributes` and code, in the form of procedures or function, often known as methods.  Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.  Object-oriented programming takes the view that what we really care about are the objects .  Examples of objects range from human beings (described by name, address, and so forth) to buildings and floors (whose properties can be described and managed) down to the little controls on a computer (such as buttons and scroll bars).
  • 4. Contd... 4  The first step in OOP is to identify all the objects the programmer wants to manipulate and how they relate to each other, an exercise often known as data modeling. Once an object has been identified, it is generalized as a class of objects which defines the kind of data it contains and any logic sequences that can manipulate it. Each distinct logic sequence is known as a method.  Simula was the first object-oriented programming language. Java, Python, C++, C# .NET and Ruby are the most popular OOP languages today.  The Java programming language is designed especially for use in distributed applications on corporate networks and the Internet.  Ruby and PHP is used in many Web applications and Web Services.  Curl, Smalltalk, Delphi and Eiffel are also examples of object-oriented programming languages.
  • 5. Contd... 5  In order to manage the classes of a software system, and to reduce the complexity, system designers use several techniques, which can be grouped under four main concepts named as :- 1. Encapsulation 2. Abstraction 3. Inheritance 4. Polymorphism. These concepts are the four main gods of OOP world and in software term, they are called four main Object Oriented Programming (OOP) Concepts.
  • 6. Benefits of OOP 6 The concepts and rules used in object-oriented programming provide these important benefits:  The concept of a data class makes it possible to define subclasses of data objects that share some or all of the main class characteristics. Called inheritance, this property of OOP forces a more thorough data analysis, reduces development time, and ensures more accurate coding.  Since a class defines only the data it needs to be concerned with, when an instance of that class (an object) is run, the code will not be able to accidentally access other program data. This characteristic of data hiding provides greater system security and avoids unintended data corruption.
  • 7. Contd... 7  The definition of a class is reusable not only by the program for which it is initially created but also by other object-oriented programs (and, for this reason, can be more easily distributed for use in networks).  The concept of data classes allows a programmer to create any new data type that is not already defined in the language itself.
  • 8. What is a Class? 8  A class is simply a representation of a type of object.  It is the blueprint, or plan, or template, that describes the details of an object.  Class is composed of three things: A name, attributes or property, and operations or method.
  • 9. What is an Object? 9  An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the Hand (object) can grip something, or a Student(object) can give their name or address.  In pure OOP terms an object is an instance of a class.  For example, the TextBox control, you always used, is made out of the TextBox class, which defines its appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new instance of the TextBox class.
  • 10. Component-based SW engineering 10  Component-based software engineering (CBSE) (also known as component-based development (CBD)) is a branch of software engineering that emphasizes the separation of concern in respect of the wide-ranging functionality available throughout a given software system.  It is a reuse-based approach to defining, implementing and composing loosely coupled independent components into systems.  All system processes are placed into separate components so that all of the data and functions inside each component are semantically related (just as with the contents of classes). Because of this principle, it is often said that components are modular and cohesive.
  • 12. Contd... 12 A simple example of several software components - pictured within a hypothetical holiday-reservation system
  • 13. Defining a Class 13  Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. <?php class SimpleClass { // declare members of class }
  • 14. Defining a Class Properties 14  Class member variables are called "properties".  You may also see them referred to using other terms such as "attributes" or "fields“  Syntax : <access type> $variable_name <?php class SimpleClass { public $name = “NIIT” // name property }
  • 15. Defining a Class Constant 15  Defining constants differ from normal variables in that you don't use the $ symbol to declare or use them.  To get constant value we use self keyword instead of $this  Always declare constant name in UPPERCASE <?php class MyClass { const CONSTANT = 'constant value'; function showConstant() { echo self::CONSTANT . "n"; } }
  • 16. Defining a Class Methods 16 Function inside a class is called as method. E.g. <?php class SimpleClass { public function sayHello() // public method { return “Hello!!!”; } }
  • 17. Accessing Object Members 17  We can access object members by using -> operator; class CollegeInfo { public $name = “NIIT”; // public property public function getCenter() // public method { return “Kathmandu”; } } //Creating Object $niit = new CollegeInfo(); // () is optional when constructor is not defined echo $niit->name // don’t use $ sign before property name echo $niit->getCenter(); // accessing method
  • 18. The $this Attribute 18  $this attribute is a self referencing object of a class.  We can access properties and method inside the method by using $this attribute e.g. <?php class StudentInfo { private $studentName = “Michio Kaku”; public function getStudentName() { // getting $studentName using $this attr return $this->studentName; } }
  • 19. What is Encapsulation? 19  Encapsulation is one of the four fundamentals of OOP  A language mechanism for restricting access to some of the object’s components  Encapsulation refers to the bundling of data with the methods that operate on that data.  Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them.  Publicly accessible methods are generally provided in the class (so- called getters and setters) to access the values, and other client classes call these methods to retrieve and modify the values within the object. Also you can specify Get access or Set access only.  Encapsulation is also known as Information Hiding
  • 20. Specifying Visibility Scope 20  We can perform encapsulation by using visibility scope  In php there are three types of visibility scopes: 1) public 2) private 3) protected  public : When a class member is defined as public that member can be access any where outside the class.  private : When a class member is defined as private that member cannot be access outside the class  protected : When a class member is defined as protected it can only be inside the class and can access by base class in Inheritance
  • 21. Constructor 21  Constructor is a type of method inside a class which gets automatically invoked on every instantiation of class.  To define constructor in php name a function __construct.  Never make constructor private, because you cannot instantiate that class if you make class constructor private make it always public <?php class MyClass { public function __construct() { // statement here will automatically executed when this class instantiates } }
  • 22. Destructor 22  Destructor is a type of method inside a class which gets automatically invoked just before destruction of the object.  To define destructor in php name a function __destruct  <?php class MyClass { public function __destruct() { // statement here will automatically executed while destroying the class } }
  • 23. PHP Magic Methods 23  PHP method that start with a double underscore “__” are called magic methods in PHP.  They are functions/methods that are always defined inside classes, and are not stand-alone (outside of classes) functions.  The magic functions available in PHP are: __construct(), __destruct(), __toString(), __invoke(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __set_state(), __clone(), and __autoload(). Why are they called magic functions? This is why they are called ‘magic’ functions – because they are never directly called, and they allow the programmer to do some pretty powerful things. The programmer must actually write the code that defines what the magic function will do. But, magic functions will never directly be called by the programmer – actually, PHP will call the function ‘behind the scenes’.
  • 24. Why use magic method? 24  To trigger some custom behavior while  attempt to call not defined methods  attempt to use object as string  etc.  Why not magic method?  3-20 times slower method call  IDE warning
  • 25. Static Members 25  Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.  We can’t call not static member inside static method.  Static members cannot be accessed through the object using the arrow operator -> we have to use scope resolution operator ‘::’ to access static members.
  • 26. Static Property 26  To define static property we have to use static keyword between access control and variable name <?php class MyClass { public static $name = “NIIT”; //static property } echo MyClass::$name;
  • 27. Static Method 27  To define static member we have to use static keyword between access control and function keyword <?php class MyClass { public static function sayHello() // static method { return “Hello!!!”; } } echo MyClass::sayHello();
  • 28. What is Inheritance? 28  Inheritance is a one of four fundamental principle oop.  The ability of a new class to be created, from an existing class by extending it, is called inheritance.  Doing this allows you to efficiently reuse the code found in your base class.  In MVC we creates MODEL by Inheriting Model abstract class and Controller by inheriting Controller abstract class E.g.1 E.g.2 class HomeController extends Controller { } we can create as many as controllers by extending Controller class
  • 29. Implementing Inheritance 29  We can inherit class by using extends keyword. class BaseClass { protected $name = “NIIT”; } class DerivedClass extends BaseClass // Inheriting BaseClass { public function getName() { return $this->name; } } $obj = new DerivedClass(); echo $obj->getName();
  • 30. What is Abstraction? 30  Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail).  The importance of abstraction is derived from its ability to hide irrelevant details.  In case of MVC we creates model by extending / inheriting Model abstract class. So get functions like where, save, findById etc. which is not declared in our derived model. That is all suppressed or defined in Model abstract class.  Commonly abstraction is performed by extending abstract class and implementing interfaces.
  • 31. Abstract Methods and Classes 31  An abstract class is a type of class that cannot be instantiated, but they can be subclassed.  An abstract class is declared using abstract keyword before class abstract class MyAbstractClass { // abstract class members }  An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon) like this: abstract function moveTo($offsetX, $offsetY);
  • 32. Contd...  If a class includes abstract methods, then the class itself must be declared abstract, as in : abstract class GraphicObject { //declare properties //declare non-abstract method abstract function draw(); }  When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract 32
  • 33. Interfaces  The term interface is often used to define an abstract type that contains no data or code, but defines behaviors as method signatures  An interface is a description of the actions that an object can do  An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class).  An interface is a shared boundary across which two separate components of a computer system exchange information.  Method defined in an interface contains no code and thus cannot itself be called; it must be implemented by class code to be run when it is invoked. 33
  • 34. Declaring & Implementing Interface  <?php interface IHand { public function moveUp($upheight); public function moveDown($downHeight); } class Hand implements IHand { public function moveUp($upHeight) { //move up code } public function moveDown($downHeight) { //move down code } } 34
  • 35. Difference Between An Interface and An Abstract Class  Interface definition begins with a keyword interface so it is of type interface  Abstract classes are declared with the abstract keyword so it is of type class  Interface has no implementation, but they have to be implemented.  Abstract class’s methods can have implementations and they have to be extended.  Interfaces can only have method declaration (public and abstract) and properties (public static)  Abstract class’s methods can’t have implementation only when declared abstract.  Abstract class can implement more than one interfaces, but can inherit only one class  Abstract class can be used to provide some default behavior for a base class. 35
  • 36. Contd...  Interface makes implementation interchangeable  Interface increase security by hiding the implementation  Abstract class can be used when implementing framework  Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies. For example, if you have an application framework, an abstract class can be used to provide the default implementation of the services and all mandatory modules such as event logging and message handling etc. This approach allows the developers to develop the application within the guided help provided by the framework. 36
  • 37. What is Polymorphism? 37  Polymorphisms is a generic term that means 'many shapes'.  More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.
  • 38. What is Method Overloading? 38  Method overloading is the ability to define several methods all with the same name.  E.g. class DB { public function connect(){ // connection code } public function connect($server, $uid, $pass, $db) { // connection code } }
  • 39. Traits 39  Traits are used to solve a problem in OOP languages such as PHP that only allow for single inheritance  It is new in PHP 5.4 <?php trait tSomeTrait { // Attributes function someFunction() { // Do whatever. } }
  • 40. Contd… 40  We can add tratis to class via the use keyword inside the class definition <?php class SomeClass { use tSomeTrait; // Rest of members. }  Now, when you createan object of type SomeClass, that object has a someFunction() method: $obj = new SomeClass(); $obj->someFunction();
  • 41. Type Hinting 41  Type hinting is the programming act of indicating what type of value is expected. For example, what type  Type hinting doesn’t play much of a role in procedural PHP code because you cannot hint simple types (e.g ., integers or strings). of value a function expects to receive for a parameter.