SlideShare a Scribd company logo
Demystifying

Object-Oriented Programming
Download Files:

https://github.com/sketchings/oop-basics
https://joind.in/talk/9b82a
Why Object-Oriented?
What’s wrong with procedural?
Terminology
the single most important part for learning
PART 1: Terms
Class
properties
methods
Object
Instance
PART 2: Terms
Abstraction
Encapsulation
Scope
PART 3: Terms
Polymorphism
Inheritance
Interface
Abstract Class
Traits
PART 4: Extra Features
Static Methods
Magic Methods
Magic Constants
Namespaces
Type Declarations
Class
Template or Blueprint
Combination of Variables and Functions
A template/blueprint that facilitates creation of objects. 

House

Human (DNA)

A set of program statements to do a certain task. 

Usually represents a noun, such as a person, place or thing. 

Includes properties (variables) and methods (functions)
Object
Entity Created from the Class
Consists of both data and procedures
Instance of a class. 

In the real world object is a material thing that can be seen and touched. 

In OOP, object is a self-contained entity that consists of both data and procedures.
Instance
Single occurrence of an object
James Titcumb (@asgrim)
There might be one or several objects, but an instance is a specific copy, to which you assign a reference

Jim, Jimmy, Jamie, Jimbo
class User { //class

private $name; //property

public function getName() { //method

echo $this->name; //current object property

}

}
$user1 = new User(); //first instance of object
$user2 = new User(); //second instance of object
PART 2: Terms
Abstraction
Hides all but the relevant data about an object in
order to reduce complexity and increase efficiency.
Use something without knowing inner workings
Managing the complexity of the system

existing in thought or as an idea but not having a physical or concrete existence.

relating to or denoting art that does not attempt to represent external reality, but rather seeks to achieve its effect using shapes, colours, and textures.

consider something theoretically or separately from (something else).

Use something like: care, computer
Encapsulation
Binds together the data
and functions that
manipulate the data, and
keeps both safe from
outside interference and
misuse.
Properties
Methods
Helps you keep things together
Scope
Controls who has access
Public - everyone
Protected - inherited classes
Private - class itself, not children
Restricting access to some of the object’s components (properties and methods), preventing unauthorized access.
LIVE CODING DEMO!
Challenges:

1. Create a new class with properties and methods

2. Instantiate a new user with a different name and title

3. Throw an error because your access is too restricted.
class User {

protected $name;

protected $title;

public function getFormattedSalutation() {

return $this->getSalutation();

}

protected function getSalutation() {

return $this->title . " " . $this->name;

}

public function getName() {

return $this->name;

}

public function setName($name) {

$this->name = $name;

}

public function getTitle() {

return $this->title;

}

public function setTitle($title) {

$this->title = $title;

}

}
Creating / Using the object Instance
$user = new User();

$user->setName("Jane Smith");

$user->setTitle("Ms");

echo $user->getFormattedSalutation();
When the script is run, it will return:
Ms Jane Smith
PART 3:
Polymorphism
D-R-Y

Sharing Code
pol·y·mor·phism
/ˌpälēˈmôrfizəm/
The condition of occurring in several different forms
BIOLOGY
GENETICS
BIOCHEMISTRY
COMPUTING
Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface
Terms
Polymorphism
Inheritance
Interface
Abstract Class
Traits
Inheritance
Pass information down
Only a single source
Subclass, parent and a child relationship, allows for reusability, extensibility. 

Additional code to an existing class without modifying it. Uses keyword “extends”

NUTSHELL: create a new class based on an existing class with more data, create new objects based on this class
LIVE CODING DEMO!
Challenge: Extend the User class for another type of user, such as our Developer example
Creating a child class
class Developer extends User {

public $skills = array(); //additional property
public function getSalutation() {//override method

return $this->title . " " . $this->name. ", Developer";

}

public function getSkillsString(){ //additional method

return implode(", ",$this->skills);

}

}
Using a child class
$developer = new Developer();

$developer->setName(”Jane Smith”);

$developer->setTitle(“Ms”);
echo $developer->getFormatedSalutation();

echo "<br />”;
$developer->skills = array("JavasScript", "HTML", "CSS");

$developer->skills[] = “PHP";
echo $developer->getSkillsString();
When run, the script returns:
Ms Jane Smith, Developer
JavasScript, HTML, CSS, PHP
Interface
Requirements for a particular TYPE of object
TIPS:
Multiple Interfaces may be implemented
All methods are public
May contain CONSTANT that cannot be overridden
Interface, specifies which methods a class must implement.

All methods in interface must be public.

Multiple interfaces can be implemented by using comma separation

Interface may contain a CONSTANT, but may not be overridden by implementing class
LIVE CODING DEMO!
Challenge: 

1. User implements UserInterface

2. Add additional interfaces for the Developer Class
interface UserInterface {
public function getFormattedSalutation();
public function getName();
public function setName($name);
public function getTitle();
public function setTitle($title);
}
class User implements UserInterface { … }
Abstract Class
Mix between an interface and a class.
Classes extending an abstract class must implement all
of the abstract methods defined in the abstract class.
It can define functionality as well as interface. 

abstract methods cannot be private because they are not a full method
LIVE CODING DEMO!
Challenge: User extend abstractUser
abstract class User { //class
public $name; //property
public function getName() { //method

echo $this->name;

}
abstract public function setName($name); //abstract method

}
class Developer extends User {

public setName($name) { //implementing the method

…
Traits
Horizontal Code Reuse
Multiple traits may be used
LIVE CODING DEMO!
Challenge: Add a trait to the User
Creating Traits
trait Toolkit {

public $tools = array();

public function setTools($task) {

switch ($task) {

case “eat":

$this->tools[] = 

array("Spoon", "Fork", "Knife");

exit;

...

}

}

public function showTools() {

return implode(", ",$this->skills);

}

}
Using Traits
class Developer extends User {

use Toolkit;

...

}
$developer = new Developer();

$developer->setName(”Jane Smith”);

$developer->setTitle(”Ms”);

echo $developer;

echo "<br />";

$developer->setTools("Eat");

echo $developer->showTools();
When run, the script returns:
Ms Jane Smith
Spoon, Fork, Knife
Part 3: Added Features
Magic Methods
Magic Constants
Static Methods
Namespaces
Type Declarations
Magic Methods
Setup just like any other method
Magic because triggered and not called
For more see http://php.net/manual/en/language.oop5.magic.php
Magic Constants
Predefined constants in PHP
For more see http://php.net/manual/en/language.constants.predefined.php
LIVE CODING DEMO!
class User {

…

public function __construct($name, $title) {

$this->name = $name;

$this->title = $title;

}



public function __toString() {

return __CLASS__. “: “

. $this->getFormattedSalutation();

}

}

$user = new User("Jane Smith","Ms");

echo $user;

When the script is run, it will return the same result as before:

User: Ms Jane Smith
Static Methods
You do NOT have to instantiate an object first
LIVE CODING DEMO!
public $encouragements = array(

“You are beautiful!”,

“You have this!”,



public static function encourage()

{

$int = rand(count($this->encouragements));

return $this->encouragements[$int];

}

echo User::encourage();

When the script is run, it will return:

You have this!
Namespaces
Prevent Code Collision
Help create a new layer of code encapsulation
Keep properties from colliding between areas of your code
Only classes, interfaces, functions and constants are affected
Anything that does not have a namespace is considered in
the Global namespace (namespace = "")
Namespaces
Must be declared first (except 'declare)
Can define multiple in the same file
You can define that something be used in the "Global"
namespace by enclosing a non-labeled namespace in {}
brackets.
Use namespaces from within other namespaces
namespace myUser;
class User { //class
public $name; //property
public getName() { //method
echo $this->name;
}
public function setName($name);
}
class Developer extends myUserUser { … }
Type Declarations
PHP 5.4
Class/Interface,
self, array,
callable
PHP 7
bool
float
int
string
Type Declarations
class Conference {

public $title;

private $attendees = array();

public function addAttendee(User $person) {

$this->attendees[] = $person;

}

public function getAttendees(): array {

foreach($this->attendees as $person) {

$attendee_list[] = $person; 

}

return $attendee_list;

}

}
Using Type Declarations
$phpuk = new Conference();

$phpuk->title = ”PHP UK Conference 2017”;

$phpuk->addAttendee($user);

echo implode(", “, $phpuk->getAttendees());
When the script is run, it will return the same result as before:
Ms Jane Smith
Challenges
1. Define 2 “User” classes. Call both classes from the same file
2. Try defining types AND try accepting/returning the wrong types
3. Try another Magic Method http://php.net/manual/en/
language.oop5.magic.php
4. Add Magic Constants http://php.net/manual/en/
language.constants.predefined.php
5. Add and use a Static Method
https://github.com/sketchings/oop-basics
Resources
LeanPub: The Essentials of Object Oriented PHP
Head First Object-Oriented Analysis and Design
Presented by: Alena Holligan
• Wife and Mother of 3 young children
• PHP Teacher at Treehouse
• Portland PHP User Group Leader
www.sketchings.com

@sketchings

alena@holligan.us
Download Files: https://github.com/sketchings/oop-basics
https://joind.in/talk/9b82a

More Related Content

PDF
Take the Plunge with OOP from #pnwphp
PDF
Demystifying Object-Oriented Programming - PHP[tek] 2017
PDF
Demystifying Object-Oriented Programming #phpbnl18
PDF
Demystifying Object-Oriented Programming - Midwest PHP
PDF
Demystifying Object-Oriented Programming - Lone Star PHP
PDF
Object Oriented Programming in PHP
PPT
Advanced php
Take the Plunge with OOP from #pnwphp
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Lone Star PHP
Object Oriented Programming in PHP
Advanced php

What's hot (20)

PDF
Demystifying oop
PPT
PHP- Introduction to Object Oriented PHP
PPT
Synapseindia object oriented programming in php
PDF
OOP in PHP
PPTX
Jscript part2
PDF
Python unit 3 m.sc cs
PPTX
Ch8(oop)
PDF
Object Oriented Programming with PHP 5 - More OOP
PPTX
Only oop
PDF
09 Object Oriented Programming in PHP #burningkeyboards
PPT
Oops in PHP
PPT
Class and Objects in PHP
PPTX
Object oriented programming in php 5
PPT
Php Oop
PPT
Class 7 - PHP Object Oriented Programming
PDF
A Gentle Introduction To Object Oriented Php
DOCX
Oops concept in php
PPTX
Object oreinted php | OOPs
PDF
PHP OOP
Demystifying oop
PHP- Introduction to Object Oriented PHP
Synapseindia object oriented programming in php
OOP in PHP
Jscript part2
Python unit 3 m.sc cs
Ch8(oop)
Object Oriented Programming with PHP 5 - More OOP
Only oop
09 Object Oriented Programming in PHP #burningkeyboards
Oops in PHP
Class and Objects in PHP
Object oriented programming in php 5
Php Oop
Class 7 - PHP Object Oriented Programming
A Gentle Introduction To Object Oriented Php
Oops concept in php
Object oreinted php | OOPs
PHP OOP
Ad

Viewers also liked (20)

PPTX
Debugging Effectively - PHP UK 2017
PDF
WordPress for the modern PHP developer
PDF
Drupal8 for Symfony Developers
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
PDF
JWT - To authentication and beyond!
PDF
PHP UK 2017 - Don't Lose Sleep - Secure Your REST
PDF
Preparing your dockerised application for production deployment
PDF
Hopping in clouds - phpuk 17
PPTX
Anti hypertensives
PPTX
How the real-time communication between things can simplify our everyday lif...
PPTX
Object-oriented programming
PDF
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
PPT
Concepts In Object Oriented Programming Languages
PPT
Object Oriented Concept
 
PDF
Integrating React.js with PHP projects
PPTX
Need of object oriented programming
PPTX
oops concept in java | object oriented programming in java
PPT
Object oriented programming (oop) cs304 power point slides lecture 01
PPT
Basic concepts of object oriented programming
PPT
Object-oriented concepts
Debugging Effectively - PHP UK 2017
WordPress for the modern PHP developer
Drupal8 for Symfony Developers
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
JWT - To authentication and beyond!
PHP UK 2017 - Don't Lose Sleep - Secure Your REST
Preparing your dockerised application for production deployment
Hopping in clouds - phpuk 17
Anti hypertensives
How the real-time communication between things can simplify our everyday lif...
Object-oriented programming
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
Concepts In Object Oriented Programming Languages
Object Oriented Concept
 
Integrating React.js with PHP projects
Need of object oriented programming
oops concept in java | object oriented programming in java
Object oriented programming (oop) cs304 power point slides lecture 01
Basic concepts of object oriented programming
Object-oriented concepts
Ad

Similar to Demystifying Object-Oriented Programming - PHP UK Conference 2017 (20)

PDF
Demystifying Object-Oriented Programming - ZendCon 2016
PDF
Demystifying Object-Oriented Programming #ssphp16
PDF
Obect-Oriented Collaboration
PDF
Lab 4 (1).pdf
PDF
OOP in PHP
PPT
Php object orientation and classes
PPTX
Intro to OOP PHP and Github
PDF
Object Oriented Programming in PHP
PPTX
Lecture-10_PHP-OOP.pptx
PPTX
UNIT III (8).pptx
PPTX
UNIT III (8).pptx
PPTX
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
PPT
Introduction to OOP with PHP
PDF
PHP: 4 Design Patterns to Make Better Code
PPSX
Oop features java presentationshow
PPTX
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
PPTX
OOPS IN PHP.pptx
PDF
Objects, Testing, and Responsibility
PPTX
Lecture 17 - PHP-Object-Orientation.pptx
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming #ssphp16
Obect-Oriented Collaboration
Lab 4 (1).pdf
OOP in PHP
Php object orientation and classes
Intro to OOP PHP and Github
Object Oriented Programming in PHP
Lecture-10_PHP-OOP.pptx
UNIT III (8).pptx
UNIT III (8).pptx
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Introduction to OOP with PHP
PHP: 4 Design Patterns to Make Better Code
Oop features java presentationshow
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
OOPS IN PHP.pptx
Objects, Testing, and Responsibility
Lecture 17 - PHP-Object-Orientation.pptx
FFW Gabrovo PMG - PHP OOP Part 3

More from Alena Holligan (20)

PDF
2023 Longhorn PHP - Learn to Succeed .pdf
PDF
Environmental variables
PDF
Dev parent
PDF
Dependency Injection
PDF
Dependency Management
PDF
Experiential Project Design
PDF
Reduce Reuse Refactor
PDF
Organization Patterns: MVC
PDF
When & Why: Interfaces, abstract classes, traits
PDF
Object Features
PDF
WordCamp Portland 2018: PHP for WordPress
PDF
Let's Talk Scope
PDF
Exploiting the Brain for Fun and Profit
PDF
Environmental Variables
PDF
Learn to succeed
PDF
Exploiting the Brain for Fun & Profit #zendcon2016
PDF
Presentation Bulgaria PHP
PDF
Presentation pnwphp
PDF
Exploiting the Brain for Fun and Profit - Lone Star 2016
PDF
Exploiting the Brain for Fun & Profit #ssphp16
2023 Longhorn PHP - Learn to Succeed .pdf
Environmental variables
Dev parent
Dependency Injection
Dependency Management
Experiential Project Design
Reduce Reuse Refactor
Organization Patterns: MVC
When & Why: Interfaces, abstract classes, traits
Object Features
WordCamp Portland 2018: PHP for WordPress
Let's Talk Scope
Exploiting the Brain for Fun and Profit
Environmental Variables
Learn to succeed
Exploiting the Brain for Fun & Profit #zendcon2016
Presentation Bulgaria PHP
Presentation pnwphp
Exploiting the Brain for Fun and Profit - Lone Star 2016
Exploiting the Brain for Fun & Profit #ssphp16

Recently uploaded (20)

PPTX
Spectroscopy.pptx food analysis technology
PPTX
Cloud computing and distributed systems.
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
Spectroscopy.pptx food analysis technology
Cloud computing and distributed systems.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Digital-Transformation-Roadmap-for-Companies.pptx
Approach and Philosophy of On baking technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Diabetes mellitus diagnosis method based random forest with bat algorithm
Mobile App Security Testing_ A Comprehensive Guide.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
Empathic Computing: Creating Shared Understanding
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
NewMind AI Weekly Chronicles - August'25 Week I
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Review of recent advances in non-invasive hemoglobin estimation

Demystifying Object-Oriented Programming - PHP UK Conference 2017

  • 3. Terminology the single most important part for learning
  • 7. PART 4: Extra Features Static Methods Magic Methods Magic Constants Namespaces Type Declarations
  • 8. Class Template or Blueprint Combination of Variables and Functions A template/blueprint that facilitates creation of objects. House Human (DNA) A set of program statements to do a certain task. Usually represents a noun, such as a person, place or thing. Includes properties (variables) and methods (functions)
  • 9. Object Entity Created from the Class Consists of both data and procedures Instance of a class. In the real world object is a material thing that can be seen and touched. In OOP, object is a self-contained entity that consists of both data and procedures.
  • 10. Instance Single occurrence of an object James Titcumb (@asgrim) There might be one or several objects, but an instance is a specific copy, to which you assign a reference Jim, Jimmy, Jamie, Jimbo
  • 11. class User { //class
 private $name; //property
 public function getName() { //method
 echo $this->name; //current object property
 }
 } $user1 = new User(); //first instance of object $user2 = new User(); //second instance of object
  • 13. Abstraction Hides all but the relevant data about an object in order to reduce complexity and increase efficiency. Use something without knowing inner workings Managing the complexity of the system existing in thought or as an idea but not having a physical or concrete existence. relating to or denoting art that does not attempt to represent external reality, but rather seeks to achieve its effect using shapes, colours, and textures. consider something theoretically or separately from (something else). Use something like: care, computer
  • 14. Encapsulation Binds together the data and functions that manipulate the data, and keeps both safe from outside interference and misuse. Properties Methods Helps you keep things together
  • 15. Scope Controls who has access Public - everyone Protected - inherited classes Private - class itself, not children Restricting access to some of the object’s components (properties and methods), preventing unauthorized access.
  • 16. LIVE CODING DEMO! Challenges: 1. Create a new class with properties and methods 2. Instantiate a new user with a different name and title 3. Throw an error because your access is too restricted.
  • 17. class User {
 protected $name;
 protected $title;
 public function getFormattedSalutation() {
 return $this->getSalutation();
 }
 protected function getSalutation() {
 return $this->title . " " . $this->name;
 }
 public function getName() {
 return $this->name;
 }
 public function setName($name) {
 $this->name = $name;
 }
 public function getTitle() {
 return $this->title;
 }
 public function setTitle($title) {
 $this->title = $title;
 }
 }
  • 18. Creating / Using the object Instance $user = new User();
 $user->setName("Jane Smith");
 $user->setTitle("Ms");
 echo $user->getFormattedSalutation(); When the script is run, it will return: Ms Jane Smith
  • 20. pol·y·mor·phism /ˌpälēˈmôrfizəm/ The condition of occurring in several different forms BIOLOGY GENETICS BIOCHEMISTRY COMPUTING Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface
  • 22. Inheritance Pass information down Only a single source Subclass, parent and a child relationship, allows for reusability, extensibility. Additional code to an existing class without modifying it. Uses keyword “extends” NUTSHELL: create a new class based on an existing class with more data, create new objects based on this class
  • 23. LIVE CODING DEMO! Challenge: Extend the User class for another type of user, such as our Developer example
  • 24. Creating a child class class Developer extends User {
 public $skills = array(); //additional property public function getSalutation() {//override method
 return $this->title . " " . $this->name. ", Developer";
 }
 public function getSkillsString(){ //additional method
 return implode(", ",$this->skills);
 }
 }
  • 25. Using a child class $developer = new Developer();
 $developer->setName(”Jane Smith”);
 $developer->setTitle(“Ms”); echo $developer->getFormatedSalutation();
 echo "<br />”; $developer->skills = array("JavasScript", "HTML", "CSS");
 $developer->skills[] = “PHP"; echo $developer->getSkillsString();
  • 26. When run, the script returns: Ms Jane Smith, Developer JavasScript, HTML, CSS, PHP
  • 27. Interface Requirements for a particular TYPE of object TIPS: Multiple Interfaces may be implemented All methods are public May contain CONSTANT that cannot be overridden Interface, specifies which methods a class must implement. All methods in interface must be public. Multiple interfaces can be implemented by using comma separation Interface may contain a CONSTANT, but may not be overridden by implementing class
  • 28. LIVE CODING DEMO! Challenge: 1. User implements UserInterface 2. Add additional interfaces for the Developer Class
  • 29. interface UserInterface { public function getFormattedSalutation(); public function getName(); public function setName($name); public function getTitle(); public function setTitle($title); } class User implements UserInterface { … }
  • 30. Abstract Class Mix between an interface and a class. Classes extending an abstract class must implement all of the abstract methods defined in the abstract class. It can define functionality as well as interface. abstract methods cannot be private because they are not a full method
  • 31. LIVE CODING DEMO! Challenge: User extend abstractUser
  • 32. abstract class User { //class public $name; //property public function getName() { //method
 echo $this->name;
 } abstract public function setName($name); //abstract method
 } class Developer extends User {
 public setName($name) { //implementing the method
 …
  • 34. LIVE CODING DEMO! Challenge: Add a trait to the User
  • 35. Creating Traits trait Toolkit {
 public $tools = array();
 public function setTools($task) {
 switch ($task) {
 case “eat":
 $this->tools[] = 
 array("Spoon", "Fork", "Knife");
 exit;
 ...
 }
 }
 public function showTools() {
 return implode(", ",$this->skills);
 }
 }
  • 36. Using Traits class Developer extends User {
 use Toolkit;
 ...
 } $developer = new Developer();
 $developer->setName(”Jane Smith”);
 $developer->setTitle(”Ms”);
 echo $developer;
 echo "<br />";
 $developer->setTools("Eat");
 echo $developer->showTools();
  • 37. When run, the script returns: Ms Jane Smith Spoon, Fork, Knife
  • 38. Part 3: Added Features Magic Methods Magic Constants Static Methods Namespaces Type Declarations
  • 39. Magic Methods Setup just like any other method Magic because triggered and not called For more see http://php.net/manual/en/language.oop5.magic.php
  • 40. Magic Constants Predefined constants in PHP For more see http://php.net/manual/en/language.constants.predefined.php
  • 41. LIVE CODING DEMO! class User { … public function __construct($name, $title) {
 $this->name = $name;
 $this->title = $title;
 }
 
 public function __toString() {
 return __CLASS__. “: “
 . $this->getFormattedSalutation();
 } } $user = new User("Jane Smith","Ms");
 echo $user; When the script is run, it will return the same result as before: User: Ms Jane Smith
  • 42. Static Methods You do NOT have to instantiate an object first
  • 43. LIVE CODING DEMO! public $encouragements = array(
 “You are beautiful!”,
 “You have this!”,
 
 public static function encourage()
 {
 $int = rand(count($this->encouragements));
 return $this->encouragements[$int];
 } echo User::encourage(); When the script is run, it will return: You have this!
  • 44. Namespaces Prevent Code Collision Help create a new layer of code encapsulation Keep properties from colliding between areas of your code Only classes, interfaces, functions and constants are affected Anything that does not have a namespace is considered in the Global namespace (namespace = "")
  • 45. Namespaces Must be declared first (except 'declare) Can define multiple in the same file You can define that something be used in the "Global" namespace by enclosing a non-labeled namespace in {} brackets. Use namespaces from within other namespaces
  • 46. namespace myUser; class User { //class public $name; //property public getName() { //method echo $this->name; } public function setName($name); } class Developer extends myUserUser { … }
  • 47. Type Declarations PHP 5.4 Class/Interface, self, array, callable PHP 7 bool float int string
  • 48. Type Declarations class Conference {
 public $title;
 private $attendees = array();
 public function addAttendee(User $person) {
 $this->attendees[] = $person;
 }
 public function getAttendees(): array {
 foreach($this->attendees as $person) {
 $attendee_list[] = $person; 
 }
 return $attendee_list;
 }
 }
  • 49. Using Type Declarations $phpuk = new Conference();
 $phpuk->title = ”PHP UK Conference 2017”;
 $phpuk->addAttendee($user);
 echo implode(", “, $phpuk->getAttendees()); When the script is run, it will return the same result as before: Ms Jane Smith
  • 50. Challenges 1. Define 2 “User” classes. Call both classes from the same file 2. Try defining types AND try accepting/returning the wrong types 3. Try another Magic Method http://php.net/manual/en/ language.oop5.magic.php 4. Add Magic Constants http://php.net/manual/en/ language.constants.predefined.php 5. Add and use a Static Method https://github.com/sketchings/oop-basics
  • 51. Resources LeanPub: The Essentials of Object Oriented PHP Head First Object-Oriented Analysis and Design
  • 52. Presented by: Alena Holligan • Wife and Mother of 3 young children • PHP Teacher at Treehouse • Portland PHP User Group Leader www.sketchings.com
 @sketchings
 [email protected] Download Files: https://github.com/sketchings/oop-basics https://joind.in/talk/9b82a