SlideShare una empresa de Scribd logo
1 de 16
FUNDAMENTALS

•Classes
•Encapsulation
•Objects
CLASS DECLARATION
The basic declaration of a class is very simple:

class myClass {
// Class contents go here
}
OBJECT INSTANTIATION
This is done by using the new construct:
$myClassInstance = new myClass();
An object is always passed by reference rather than by value.
$myClassInstance = new myClass();
$copyInstance = $myClassInstance();
CLASS INHERITANCE
Allows a class to extend another class, essentially adding new methods and properties, as well as
overriding existing ones as needed.
class a {
function test()
{
echo "a::test called";
}
function func()
{
echo "a::func called";
}
}
class b extends a {
function test()
{
echo "b::test called";
}
}

class c extends b {
function test()
{
parent::test();
}
}
class d extends c {
function test()
{
b::test();
}
}
$a = new a();
$b = new b();
$c = new c();
$d = new d();
METHODS AND PROPERTIES
Methods are declared just like traditional functions:
class myClass {
function myFunction() {
echo "You called myClass::myFunction";
}

}
From outside the scope of a class, its methods are called using the indirection operator ->:
$obj = new myClass();
$obj->myFunction();
METHODS AND PROPERTIES
class myClass {
function myFunction($data) {
echo "The value is $data";
}

function callMyFunction($data) {
// Call myFunction()
$this->myFunction($data);

}

}

$obj = new myClass();
$obj->callMyFunction(123);
CONSTRUCTORS
class foo {
function __construct()
{
echo __METHOD__;
}
function foo()
{
// PHP 4 style constructor
}
}
new foo();
DESTRUCTORS
class foo {
function __construct()
{
echo __METHOD__ . PHP_EOL;
}
function __destruct()
{
echo __METHOD__;
}
}
new foo();

This code will display:
foo::__construct
foo::__destruct
VISIBILITY
public

The resource can be accessed from any scope.

protected

The resource can only be accessed from within the class where it is
defined and its descendants.

private

The resource can only be accessed from within the class where it is
defined.
The resource is accessible from any scope, but cannot be
overridden in descendant classes.

final
DECLARING AND ACCESSING PROPERTIES
class foo {
public $bar;
protected $baz;
private $bas;

public $var1 = "Test"; // String
public $var2 = 1.23; // Numeric value
public $var3 = array (1, 2, 3);

}
CONSTANTS, STATIC METHODS AND
PROPERTIES
class foo {
static $bar = "bat";
public static function baz()
{
echo "Hello World";
}
}
$foo = new foo();
$foo->baz();
echo $foo->bar;

Hello WorldPHP Strict Standards: Accessing static
property foo::$bar as non static in PHPDocument1
on line 17
Strict Standards: Accessing static property
foo::$bar as non static in PHPDocument1 on line 1
CLASS CONSTANTS
class foo {

const BAR = "Hello World";
}
echo foo::BAR;
INTERFACES AND ABSTRACT CLASSES
•An abstract class essentially defines the basic skeleton of a
specific type of encapsulated entity.

•Interfaces, on the other hand, are used to specify an API that
a class must implement.
EXCEPTIONS

• Exceptions provide an error control mechanism that is more fine-grained than
traditional PHP fault handling, and that allows for a much greater degree of control.

• Key differences between “regular” PHP errors and exceptions:
• Exceptions are objects, created (or “thrown”) when an error occurs
• Exceptions can be handled at different points in a script’s execution, and different
types of exceptions can be handled by separate portions of a script’s code

• All unhandled exceptions are fatal
• Exceptions can be thrown from the __construct method on failure
• Exceptions change the flow of the application
OOP in PHP

Más contenido relacionado

La actualidad más candente

A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
Michael Girouard
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
Rajesh S
 
Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 

La actualidad más candente (19)

A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
 
Scripting3
Scripting3Scripting3
Scripting3
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regex
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
29csharp
29csharp29csharp
29csharp
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 

Destacado (7)

Establishing a Web Presence
Establishing a Web PresenceEstablishing a Web Presence
Establishing a Web Presence
 
Website Security
Website SecurityWebsite Security
Website Security
 
Cryptography
CryptographyCryptography
Cryptography
 
Getting started with Android Programming
Getting started with Android ProgrammingGetting started with Android Programming
Getting started with Android Programming
 
Elements of Object-oriented Design
Elements of Object-oriented DesignElements of Object-oriented Design
Elements of Object-oriented Design
 
Creative Thinking
Creative ThinkingCreative Thinking
Creative Thinking
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
 

Similar a OOP in PHP

Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 

Similar a OOP in PHP (20)

Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Inheritance
InheritanceInheritance
Inheritance
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Web 9 | OOP in PHP
Web 9 | OOP in PHPWeb 9 | OOP in PHP
Web 9 | OOP in PHP
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find Useful
 
oop database doc for studevsgdy fdsyn hdf
oop database doc for studevsgdy fdsyn hdfoop database doc for studevsgdy fdsyn hdf
oop database doc for studevsgdy fdsyn hdf
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Only oop
Only oopOnly oop
Only oop
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
php_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdfphp_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdf
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 

Más de Henry Osborne

Más de Henry Osborne (20)

Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
 
Open Source Education
Open Source EducationOpen Source Education
Open Source Education
 
Security Concepts - Linux
Security Concepts - LinuxSecurity Concepts - Linux
Security Concepts - Linux
 
Networking Basics with Linux
Networking Basics with LinuxNetworking Basics with Linux
Networking Basics with Linux
 
Disk and File System Management in Linux
Disk and File System Management in LinuxDisk and File System Management in Linux
Disk and File System Management in Linux
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
HTML5 Multimedia Support
HTML5 Multimedia SupportHTML5 Multimedia Support
HTML5 Multimedia Support
 
Information Architecture
Information ArchitectureInformation Architecture
Information Architecture
 
Interface Design
Interface DesignInterface Design
Interface Design
 
Universal Usability
Universal UsabilityUniversal Usability
Universal Usability
 
XML and Web Services
XML and Web ServicesXML and Web Services
XML and Web Services
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
Web Programming
Web ProgrammingWeb Programming
Web Programming
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
 
Web Programming and Internet Technologies
Web Programming and Internet TechnologiesWeb Programming and Internet Technologies
Web Programming and Internet Technologies
 
Angels & Demons
Angels & DemonsAngels & Demons
Angels & Demons
 
Social Media and You
Social Media and YouSocial Media and You
Social Media and You
 
JCS Presentation
JCS PresentationJCS Presentation
JCS Presentation
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

OOP in PHP

  • 1.
  • 3. CLASS DECLARATION The basic declaration of a class is very simple: class myClass { // Class contents go here }
  • 4. OBJECT INSTANTIATION This is done by using the new construct: $myClassInstance = new myClass(); An object is always passed by reference rather than by value. $myClassInstance = new myClass(); $copyInstance = $myClassInstance();
  • 5. CLASS INHERITANCE Allows a class to extend another class, essentially adding new methods and properties, as well as overriding existing ones as needed. class a { function test() { echo "a::test called"; } function func() { echo "a::func called"; } } class b extends a { function test() { echo "b::test called"; } } class c extends b { function test() { parent::test(); } } class d extends c { function test() { b::test(); } } $a = new a(); $b = new b(); $c = new c(); $d = new d();
  • 6. METHODS AND PROPERTIES Methods are declared just like traditional functions: class myClass { function myFunction() { echo "You called myClass::myFunction"; } } From outside the scope of a class, its methods are called using the indirection operator ->: $obj = new myClass(); $obj->myFunction();
  • 7. METHODS AND PROPERTIES class myClass { function myFunction($data) { echo "The value is $data"; } function callMyFunction($data) { // Call myFunction() $this->myFunction($data); } } $obj = new myClass(); $obj->callMyFunction(123);
  • 8. CONSTRUCTORS class foo { function __construct() { echo __METHOD__; } function foo() { // PHP 4 style constructor } } new foo();
  • 9. DESTRUCTORS class foo { function __construct() { echo __METHOD__ . PHP_EOL; } function __destruct() { echo __METHOD__; } } new foo(); This code will display: foo::__construct foo::__destruct
  • 10. VISIBILITY public The resource can be accessed from any scope. protected The resource can only be accessed from within the class where it is defined and its descendants. private The resource can only be accessed from within the class where it is defined. The resource is accessible from any scope, but cannot be overridden in descendant classes. final
  • 11. DECLARING AND ACCESSING PROPERTIES class foo { public $bar; protected $baz; private $bas; public $var1 = "Test"; // String public $var2 = 1.23; // Numeric value public $var3 = array (1, 2, 3); }
  • 12. CONSTANTS, STATIC METHODS AND PROPERTIES class foo { static $bar = "bat"; public static function baz() { echo "Hello World"; } } $foo = new foo(); $foo->baz(); echo $foo->bar; Hello WorldPHP Strict Standards: Accessing static property foo::$bar as non static in PHPDocument1 on line 17 Strict Standards: Accessing static property foo::$bar as non static in PHPDocument1 on line 1
  • 13. CLASS CONSTANTS class foo { const BAR = "Hello World"; } echo foo::BAR;
  • 14. INTERFACES AND ABSTRACT CLASSES •An abstract class essentially defines the basic skeleton of a specific type of encapsulated entity. •Interfaces, on the other hand, are used to specify an API that a class must implement.
  • 15. EXCEPTIONS • Exceptions provide an error control mechanism that is more fine-grained than traditional PHP fault handling, and that allows for a much greater degree of control. • Key differences between “regular” PHP errors and exceptions: • Exceptions are objects, created (or “thrown”) when an error occurs • Exceptions can be handled at different points in a script’s execution, and different types of exceptions can be handled by separate portions of a script’s code • All unhandled exceptions are fatal • Exceptions can be thrown from the __construct method on failure • Exceptions change the flow of the application

Notas del editor

  1. OOP revolves around the concept of grouping code and data together in logical units called classesThis process is usually referred to as encapsulation, or information hidingClasses are essentially a representation of a set of functions (also called methods) and variables (called properties) designed to work together and to provide a specific interface to the outside worldClasses are just blueprints that must be instantiated into objects
  2. This advises the PHP interpreter that you are declaring a class called myClass whose contents will normally be a combination of constants, variables and functions (called methods)
  3. $a->test(); // Outputs "a::test called"$b->test(); // Outputs "b::test called"$b->func(); // Outputs "a::func called"$c->test(); // Outputs "b::test called"$d->test(); // Outputs "b::test called"
  4. How do you reference a class’ method from within the class itself?PHP defines a special variable called $this; this variable is only defined within an object’s scope, and always points to the object itself
  5. PHP 5 now uses the magic __construct() method as the constructor for any class regardless of the class’ nameThis example will display foo::__construct (the__METHOD__constant is replaced at compilation time with the name of the current class method). Note that, if the __construct() method is not found, PHP will look for the old PHP 4-style constructor (foo) and call that instead.
  6. This works like a mirror image of __construct(): it is called right before an object is destroyed, and is useful for performing cleanup procedures—such as disconnecting from a remote resource, or deleting temporary files
  7. N.B. The final visibility level only applies to methods and classes. Classes that are declared as final cannot be extended.
  8. Note that, like a normal variable, a class property can be initialized while it is being declared. However, the initialization is limited to assigning values (but not by evaluating expressions). You can’t, for example, initialize a variable by calling a function—that’s something you can only do within one of the class’ methods (typically, the constructor).
  9. PHP is very strict about the use of static properties; calling static properties using object notation (i.e. $obj->property) will result in both a “strict standards” message and a notice.
  10. Class constants work in the same way as regular constants, except they are scoped within a class. Class constants are public, and accessible from all scopes; for example, the following script will output Hello World
  11. An abstract class essentially defines the basic skeleton of a specific type of encapsulated entity—for example, you can use an abstract class to define the basic concept of “car” as having two doors, a lock and a method that locks or unlocks the doors. Abstract classes cannot be used directly, but they must be extended so that the descendent class provides a full complement of methods.Interfaces, on the other hand, are used to specify an API that a class must implement. This allows you to create a common “contract” that your classes must implement in order to satisfy certain logical requirements—for example, you could use interfaces to abstract the concept of database provider into a common API that could then be implemented by a series of classes that interface to different DBMSs