KEMBAR78
Demystifying Object-Oriented Programming - PHP[tek] 2017 | PDF
PHP[TEK] 2017
Wifi:
Sheraton Meeting
Network

Pass: php2017

Twitter:
#phptek
Rate the talks
https://joind.in/event/phptek-2017
Demystifying

Object-Oriented Programming
Download Files:

https://github.com/sketchings/oop-basics
https://joind.in/talk/6cf9b
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
PART 1: Terminology
Class (properties, methods)
Object
Instance
Abstraction
Encapsulation
PART 2: Polymorphism
Inheritance
Interface
Abstract Class
Traits
PART 3: Magic
Magic Methods
Magic Constants
Static Properties and Methods
PART 4: Scope
Property and Method Scope
Finality
Namespaces
Type Declarations
PART 1: Terminology
Class
A template/blueprint that facilitates creation of
objects. A set of program statements to do a certain
task. Usually represents a noun, such as a person,
place or thing.
Includes properties and methods — which are class
functions
Object
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/copy of an object
There might be one or several objects, but an
instance is a specific copy, to which you can have a
reference
class User { //class

public $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
Abstraction
Managing the complexity of the system
Dealing with ideas rather than events
This is the class architecture itself.
Use something without knowing inner workings
Encapsulation
Binds together the data
and functions that
manipulate the data, and
keeps both safe from
outside interference and
misuse.
Properties
Methods
Team-up
OOP is great for working in groups
Team Challenges
Write a class with properties and methods
Example: User class with name, title, and salutation
PART 2:
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
Terms
Polymorphism
Inheritance
Interface
Abstract Class
Traits
Inheritance: passes knowledge down
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
Creating a child class
class Developer extends User {

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

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

}
public function getSalutation() {//override method

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

}

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

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

$developer->setTitle(“Ms”);

echo $developer->getFormatedSalutation();
$developer->skills = array("JavasScript", "HTML", "CSS");

$developer->skills[] = “PHP";

echo $developer->getSkillsString();
When the script is run, it will return:
Ms Jane Smith, Developer
JavasScript, HTML, CSS, PHP
Team Challenges
Extend the User class for another type of user, such as our
Developer example
Interface
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
interface UserInterface {
public function getFormattedSalutation();
public function getName();
public function setName($name);
public function getTitle();
public function setTitle($title);
}
class User implements UserInterface { … }
Team Challenges
Add an Interface for your Class
Abstract Class
An abstract class is a mix between an interface and a
class. It can define functionality as well as interface.
Classes extending an abstract class must implement all
of the abstract methods defined in the abstract class.
abstract class User { //abstract class
public $name; //class property
public getName() { //class method

echo $this->name;

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

}
class Developer extends User {

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

…
Team Challenges
Change to User class to an abstract class.
Try instantiating the User class
Traits
Composition
Horizontal Code Reuse
Multiple traits can be implemented
Creating Traits
trait Toolkit {

public $tools = array();

public function setTools($task) {

switch ($task) {

case “eat":

$this->tools = 

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

break;

...

}

}

public function showTools() {

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

}

}
Using Traits
class Developer extends User {

use Toolkit;

...

}
$developer = new Developer();

$developer->setTools("Eat");

echo $developer->showTools();
When run the script returns:
Spoon, Fork, Knife
When run, the script returns:
Ms Jane Smith
Spoon, Fork, Knife
Team Challenges
Add a trait to the User
PART 3: Magic
Magic Methods
Magic Constants
Static Properties and Methods
Magic Methods
Setup just like any other method
The Magic comes from the fact that they are
triggered and not called
For more see http://php.net/manual/en/
language.oop5.magic.php
Magic Constants
Predefined functions in PHP
For more see http://php.net/manual/en/
language.constants.predefined.php
Using Magic Methods and Constants
class User {
...



public function __construct($name, $title) {

$this->name = $name;

$this->title = $title;

}



public function __toString() {

return __CLASS__. “: “

. $this->getFormattedSalutation();

}

...

}
Creating / Using the Magic Method
$user = new User("Jane Smith","Ms");

echo $user;
When the script is run, it will return:
User: Ms Jane Smith
Challenges
Add a Magic Method
Add a Magic Constants
Static Properties and Methods
class User {

public static $encouragements = array(

“You are beautiful!”,

“You have this!”,



public static function encourage()

{

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

return self::encouragements[$int];

}

...

}
Using the Static Method
echo User::encourage();
When the script is run, it will return:
You have this!
Team Challenge
Add and use a Static Method
Part 3: Scope
Property and Method Scope
Finality
Namespaces
Type Declarations
Property and Method Scope
Controls who can access what. Restricting access to
some of the object’s components (properties and
methods), preventing unauthorized access.
Public - everyone
Protected - inherited classes
Private - class itself, not children
class User {

private $name;

protected $title;

public function getFormattedSalutation() {

return $this->getSalutation();

}

protected function getSalutation() {

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

}
class Developer extends User {

private $name; //second property

protected $title; //override property

public function getSalutation() {

return parent::getSalutation() 

. ", Developer";

}
Creating / Using the object Instance
$developer = new Developer(

"Jane Smith”,”Ms"

);

echo $developer->getFormattedSalutation();
When the script is run, it will return:
Ms Jane Smith, Developer
Team Challenges
Restrict properties
Restrict a method
The FINAL Keyword
Prevents child classes from overriding a method by
prefixing the definition with final.
If the class itself is being defined final then it cannot
be extended.
class User { //can extend

final public getName() { //cannot extend

echo $this->name;

}
final class Developer extends User { //cannot extend

public getName() { //error

echo “My Name is: ” .$this->name;

}
class Manager extends Developer {…} //error
Team Challenges
Define a parent method as FINAL and try to override in the child
Define a class as FINAL and try to create a child
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, along with
aliasing
//can build
namespace myUser;
class User {

…

}
//utilize
use myUser;
class Developer extends myUserUser

{

… 

}
Team Challenge
Defining types AND try accepting/returning the wrong types
Available 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
$tek = new Conference();

$tek->title = ”PHP[tek] 2017”;

$tek->addAttendee($user);

echo $tek->title;

echo implode(", “, $tek->getAttendees());
When the script is run, it will return the same result as before:
PHP[tek] 2017

Ms Jane Smith
Team Challenge
Defining types AND try accepting/returning the wrong types
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/6cf9b

Demystifying Object-Oriented Programming - PHP[tek] 2017

  • 1.
    PHP[TEK] 2017 Wifi: Sheraton Meeting Network
 Pass:php2017
 Twitter: #phptek Rate the talks https://joind.in/event/phptek-2017
  • 2.
  • 3.
    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
  • 4.
    PART 1: Terminology Class(properties, methods) Object Instance Abstraction Encapsulation
  • 5.
  • 6.
    PART 3: Magic MagicMethods Magic Constants Static Properties and Methods
  • 7.
    PART 4: Scope Propertyand Method Scope Finality Namespaces Type Declarations
  • 8.
  • 9.
    Class A template/blueprint thatfacilitates creation of objects. A set of program statements to do a certain task. Usually represents a noun, such as a person, place or thing. Includes properties and methods — which are class functions
  • 10.
    Object Instance of aclass. 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.
  • 11.
    Instance Single occurrence/copy ofan object There might be one or several objects, but an instance is a specific copy, to which you can have a reference
  • 12.
    class User {//class
 public $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 Managing the complexityof the system Dealing with ideas rather than events This is the class architecture itself. Use something without knowing inner workings
  • 14.
    Encapsulation Binds together thedata and functions that manipulate the data, and keeps both safe from outside interference and misuse. Properties Methods
  • 15.
    Team-up OOP is greatfor working in groups
  • 16.
    Team Challenges Write aclass with properties and methods Example: User class with name, title, and salutation
  • 17.
  • 18.
    pol·y·mor·phism /ˌpälēˈmôrfizəm/ The condition ofoccurring in several different forms BIOLOGY GENETICS BIOCHEMISTRY COMPUTING
  • 19.
  • 20.
    Inheritance: passes knowledgedown 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
  • 21.
    Creating a childclass class Developer extends User {
 public $skills = array(); //additional property public function getSkillsString(){ //additional method
 return implode(", ",$this->skills);
 } public function getSalutation() {//override method
 return $this->title . " " . $this->name. ", Developer";
 }
 }
  • 22.
    Using a childclass $developer = new Developer();
 $developer->setName(”Jane Smith”);
 $developer->setTitle(“Ms”);
 echo $developer->getFormatedSalutation(); $developer->skills = array("JavasScript", "HTML", "CSS");
 $developer->skills[] = “PHP";
 echo $developer->getSkillsString(); When the script is run, it will return: Ms Jane Smith, Developer JavasScript, HTML, CSS, PHP
  • 23.
    Team Challenges Extend theUser class for another type of user, such as our Developer example
  • 24.
    Interface Interface, specifies whichmethods 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
  • 25.
    interface UserInterface { publicfunction getFormattedSalutation(); public function getName(); public function setName($name); public function getTitle(); public function setTitle($title); } class User implements UserInterface { … }
  • 26.
    Team Challenges Add anInterface for your Class
  • 27.
    Abstract Class An abstractclass is a mix between an interface and a class. It can define functionality as well as interface. Classes extending an abstract class must implement all of the abstract methods defined in the abstract class.
  • 28.
    abstract class User{ //abstract class public $name; //class property public getName() { //class method
 echo $this->name;
 } abstract public function setName($name); //abstract method
 } class Developer extends User {
 public setName($name) { //implementing the method
 …
  • 29.
    Team Challenges Change toUser class to an abstract class. Try instantiating the User class
  • 30.
  • 31.
    Creating Traits trait Toolkit{
 public $tools = array();
 public function setTools($task) {
 switch ($task) {
 case “eat":
 $this->tools = 
 array("Spoon", "Fork", "Knife");
 break;
 ...
 }
 }
 public function showTools() {
 return implode(", ",$this->skills);
 }
 }
  • 32.
    Using Traits class Developerextends User {
 use Toolkit;
 ...
 } $developer = new Developer();
 $developer->setTools("Eat");
 echo $developer->showTools(); When run the script returns: Spoon, Fork, Knife
  • 33.
    When run, thescript returns: Ms Jane Smith Spoon, Fork, Knife
  • 34.
    Team Challenges Add atrait to the User
  • 35.
    PART 3: Magic MagicMethods Magic Constants Static Properties and Methods
  • 36.
    Magic Methods Setup justlike any other method The Magic comes from the fact that they are triggered and not called For more see http://php.net/manual/en/ language.oop5.magic.php
  • 37.
    Magic Constants Predefined functionsin PHP For more see http://php.net/manual/en/ language.constants.predefined.php
  • 38.
    Using Magic Methodsand Constants class User { ...
 
 public function __construct($name, $title) {
 $this->name = $name;
 $this->title = $title;
 }
 
 public function __toString() {
 return __CLASS__. “: “
 . $this->getFormattedSalutation();
 }
 ...
 }
  • 39.
    Creating / Usingthe Magic Method $user = new User("Jane Smith","Ms");
 echo $user; When the script is run, it will return: User: Ms Jane Smith
  • 40.
    Challenges Add a MagicMethod Add a Magic Constants
  • 41.
    Static Properties andMethods class User {
 public static $encouragements = array(
 “You are beautiful!”,
 “You have this!”,
 
 public static function encourage()
 {
 $int = rand(count($this->encouragements));
 return self::encouragements[$int];
 }
 ...
 }
  • 42.
    Using the StaticMethod echo User::encourage(); When the script is run, it will return: You have this!
  • 43.
    Team Challenge Add anduse a Static Method
  • 44.
    Part 3: Scope Propertyand Method Scope Finality Namespaces Type Declarations
  • 45.
    Property and MethodScope Controls who can access what. Restricting access to some of the object’s components (properties and methods), preventing unauthorized access. Public - everyone Protected - inherited classes Private - class itself, not children
  • 46.
    class User {
 private$name;
 protected $title;
 public function getFormattedSalutation() {
 return $this->getSalutation();
 }
 protected function getSalutation() {
 return $this->title . " " . $this->name;
 } class Developer extends User {
 private $name; //second property
 protected $title; //override property
 public function getSalutation() {
 return parent::getSalutation() 
 . ", Developer";
 }
  • 47.
    Creating / Usingthe object Instance $developer = new Developer(
 "Jane Smith”,”Ms"
 );
 echo $developer->getFormattedSalutation(); When the script is run, it will return: Ms Jane Smith, Developer
  • 48.
  • 49.
    The FINAL Keyword Preventschild classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
  • 50.
    class User {//can extend
 final public getName() { //cannot extend
 echo $this->name;
 } final class Developer extends User { //cannot extend
 public getName() { //error
 echo “My Name is: ” .$this->name;
 } class Manager extends Developer {…} //error
  • 51.
    Team Challenges Define aparent method as FINAL and try to override in the child Define a class as FINAL and try to create a child
  • 52.
    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 = "")
  • 53.
    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, along with aliasing
  • 54.
    //can build namespace myUser; classUser {
 …
 } //utilize use myUser; class Developer extends myUserUser
 {
 … 
 }
  • 55.
    Team Challenge Defining typesAND try accepting/returning the wrong types
  • 56.
    Available Type Declarations PHP5.4 Class/Interface, self, array, callable PHP 7 bool float int string
  • 57.
    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;
 }
 }
  • 58.
    Using Type Declarations $tek= new Conference();
 $tek->title = ”PHP[tek] 2017”;
 $tek->addAttendee($user);
 echo $tek->title;
 echo implode(", “, $tek->getAttendees()); When the script is run, it will return the same result as before: PHP[tek] 2017
 Ms Jane Smith
  • 59.
    Team Challenge Defining typesAND try accepting/returning the wrong types
  • 60.
    Resources LeanPub: The Essentialsof Object Oriented PHP Head First Object-Oriented Analysis and Design
  • 61.
    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/6cf9b