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

Demystifying Object-Oriented Programming - PHP UK Conference 2017

  • 1.
  • 2.
  • 3.
    Terminology the single mostimportant part for learning
  • 4.
  • 5.
  • 6.
  • 7.
    PART 4: ExtraFeatures Static Methods Magic Methods Magic Constants Namespaces Type Declarations
  • 8.
    Class Template or Blueprint Combinationof 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 fromthe 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 ofan 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
  • 12.
  • 13.
    Abstraction Hides all butthe 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 thedata 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 hasaccess 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 / Usingthe 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
  • 19.
  • 20.
    pol·y·mor·phism /ˌpälēˈmôrfizəm/ The condition ofoccurring 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
  • 21.
  • 22.
    Inheritance Pass information down Onlya 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 childclass 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 childclass $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, thescript returns: Ms Jane Smith, Developer JavasScript, HTML, CSS, PHP
  • 27.
    Interface Requirements for aparticular 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 { publicfunction getFormattedSalutation(); public function getName(); public function setName($name); public function getTitle(); public function setTitle($title); } class User implements UserInterface { … }
  • 30.
    Abstract Class Mix betweenan 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
 …
  • 33.
  • 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 Developerextends 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, thescript returns: Ms Jane Smith Spoon, Fork, Knife
  • 38.
    Part 3: AddedFeatures Magic Methods Magic Constants Static Methods Namespaces Type Declarations
  • 39.
    Magic Methods Setup justlike 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 constantsin PHP For more see http://php.net/manual/en/language.constants.predefined.php
  • 41.
    LIVE CODING DEMO! classUser { … 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 doNOT 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 Helpcreate 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 declaredfirst (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 Essentialsof Object Oriented PHP Head First Object-Oriented Analysis and Design
  • 52.
    Presented by: AlenaHolligan • 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