SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Object Features
1. Access Control
2. Managing Types
3. Namespacing and Autoloading
4. Exceptions
PART 1: Access Control
Scope
Visibility: Public, Private, Protected
State: Static, Final
Magic
Personal Scope
Acquaintance (Social)
Friends
Professional
Family
Romantic
“MOM!”
“MOM!”
Visibility
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
Children can be more restrictive but NOT less restrictive
class User {

public $lang = "en"; //public

private $name = “Guest"; //private

protected $greeting = [ ‘en’ => “Welcome”, ‘sp’ => “Hola” ]; //protected

public function getSalutation($lang = null) { //polymorphic method

$lang = $this->getLang($lang); //abstracting

return $this->greeting[$lang] . " " . $this->name;

}

protected function getLanguage($lang) { //reuse

if (!array_key_exists($lang, $this->greeting)) $lang = $this->lang;

return $lang;

}

public function setName($name) { //setter

$this->name = ucwords($name); //control formatting

}

public function getName() { //getter

return $this->name; //can access private

}

}
Accessing Visibility
$guest = new User();

echo $guest->getSalutation();

//$guest->name = "alena"; //private not accessible

$guest->setName("alena");

//$guest->greeting = "Hello";//protected not accessible

echo $guest->getSalutation(‘sp’);

echo "Hello " . $guest->getName();
When the script is run, it will return:
Welcome GuestHola AlenaHello Alena
Accessed by a child class
class Developer extends User {

public $name = "Programmer";//new property

protected $greeting = "Hello";//overridable, not private

//override method

public function getSalutation($lang = null) {//same params

return $this->greeting //protected child string

." ".$this->getName() //private parent

.", Developer";

}

...

}
Accessing Child Visibility
$developer = new Developer();

echo $developer->name;//child $name

$developer->name = "tiberias";//child $name

echo $developer->name;//child $name

echo $developer->getName();//parent $name

//ProgrammertiberiasGuest
echo $developer->getSalutation();//child $greeting, parent $name

//Hello Guest, Developer
$developer->setName("alena");//parent $name

echo $developer->name;//child $name

echo $developer->getName();//parent $name

//tiberiasAlena
echo $developer->getSalutation();//child $greeting, parent $name

//Hello Alena, Developer
QUESTIONS
State
Static
Do not need to instantiate an object
Static methods must be public
Internal Access: self::, parent::, static::
Late static bindings: class that’s calling
Final
Methods cannot be overridden
Class cannot be extended
class User {
...
protected static $encouragements = array(

"You are beautiful!",

"You have this!"

);



final public static function encourage() { 

//Late Static Bindings, class that’s calling

$int = rand(1, count(static::$encouragements));

return static::$encouragements[$int-1];

}

}
final class Developer extends User {

...

private static $encouragements = array(

"You are not your code",

"There has never been perfect software"

);



public static function encourage() { 

//error parent was final

}

public static function devEncourage() {

$int = rand(1, count(self::$encouragements));

return self::$encouragements[$int-1];

}

public static function userEncourage() {

$int = rand(1, count(parent::$encouragements));

return parent::$encouragements[$int-1];

}

}
Calling State
//echo User::$encouragements[0];//Error protected

echo Developer::$encouragements[0];

echo User::encourage();//User (static::)

echo Developer::encourage();//Developer (static::)

echo Developer::devEncourage();//Developer (self::)

echo Developer::userEncourage();//User (parent::)

class Architect extends Developer {

//Error: Developer is final

}
When the script is run, it will return:

You are beautiful!You are beautiful!You are not your code!There has never been perfect
software.You have this!
class Developer extends User {

...

//must match array type of parent

protected $greeting = [ ‘en’ => “Hello”, ‘sp’ => “Hola” ];

public function getSalutation($lang = ‘en’) { //extended

$salutation = parent::getSaluation($lang); //not a static call

return $salutation . ", Developer";

}

}
$developer = new Developer();

$developer->setName("alena");

echo $developer->getSalutation();
When the script is run, it will return:
Hello Alena, Developer
QUESTIONS
Magic
Magic Methods
Magic Constants
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 constants 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) {

$this->setName($name);

}



public function __toString() {

return __CLASS__. “: “

. $this->getSalutation();

}

...

}
Invoking the Magic
$alena = new User("alena");

echo $alena;
$tiberias = new Developer("tiberias");

echo $tiberias;
When the script is run, it will return:
User: Welcome Alena

Developer: Welcome Tiberias, Developer
Magic Setter Trait
trait SettersTrait {

public function __set($name, $value) { //magic method

$setter = 'set'.$name; //creating method name

if (method_exists($this, $setter)) {

$this->$setter($value); //variable function or method

//$this->{‘set’.$name}; //optionally use curly braces

} else {

$this->$name = $value; //variable variable or property 

}

}

}
QUESTIONS
PART 2: Managing Types
Type Declarations (Hints)
Return Types
Type Juggling
Strict Types
class User {

…

public function getSalutation(string $lang = null) { //accept string, null or nothing

$lang = $this->getLang($lang);

return $this->greeting[$lang] . " " . $this->name;

}

public function getLanguage(?string $lang) { //accept string or null

if (!array_key_exists($lang, $this->greeting)) $lang = $this->lang;

return $lang;

}

public function setName(string $name) { //accept string only

$this->name = ucwords($name);

}

public function setName(string $name) {//accept string only

$this->name = ucwords($name);

}

public function getName() {

return $this->name;

}

public function setGreeting(array $greeting){ //accept array only

$this->greeting = $greeting;

}

}
class User {

…

public function getSalutation(string $lang = null): string { //return string

$lang = $this->getLang($lang);

return $this->greeting[$lang] . " " . $this->name;

}

public function getLanguage(?string $lang): ?string { //return string or null

if (!array_key_exists($lang, $this->greeting)) $lang = $this->lang;

return $lang;

}

public function setName(string $name): void { //no return

$this->name = ucwords($name);

return; //this is void as well

}

public function setName(string $name): void {//no return

$this->name = ucwords($name);

}

public function getName(): string {

return $this->name;

}

public function setGreeting(array $greeting): void { //no return

$this->greeting = $greeting;

}

}
Type Juggling
//By default, scalar type-declarations are non-strict
class User {

…

public function setName(string $name): void { //will attempt to convert to string

$this->name = ucwords($name);

}

}
$guest = new User(1);

var_dump($guest->getName());

// string(1) "1"
Type Juggling
//By default, scalar type-declarations are non-strict
class User {

…

public function getName(): string {

return 2; // will convert to return string

}

}
$guest = new User(1);

var_dump($guest->getName());

// string(1) “2"
Type Juggling
//By default, scalar type-declarations are non-strict
class User {

…

public function setGreeting(array $greeting): void { //getter

$this->greeting = $greeting; //can access private

}

}
$guest = new User(1);

$guest->setGreeting("Greetings");

// TypeError: Argument 1 passed to User::setGreeting() must be of the type array, string given
Strict Types
declare(strict_types=1);
class User {

…

public function setName(string $name): void { //MUST pass string

$this->name = ucwords($name);

}

}
$guest = new User(1);

//TypeError: Argument 1 passed to User::setName() must be of the type string, integer
given
Strict Types
declare(strict_types=1);
class User {

…

public function getName(): string { //MUST return type string

return 2; //attempt int

}

}
$guest = new User();

$guest->getName();

//TypeError: Return value of User::getName() must be of the type string, integer returned
QUESTIONS
PART 3: Namespacing
Namespacing
SHOULD Separate files for each class, interface, and trait
Add to the top of each file 

namespace sketchingsoop;
When calling a class file link to full path or ‘use’ path
Default namespace is current namespace
No namespace is global namespace ‘’
Namespace: Directory
classes
Developer.php
sketching
oop
SettersTrait.php
User.php
UserInterface.php
index.php
Setting Namespaces
//classes/sketchings/oop/User.php: namespace referencing same namespace

namespace sketchingsoop;

class User implements UserInterface {…}
//classes/Developer.php: OPTION 1 use path

use sketchingsoopUser;

class Developer extends User {…}
//classes/Developer.php: OPTION 2 full path

class Developer extends sketchingsoopUser {…}
Using Namespaces: index.php
<?php

require_once 'classes/sketchings/oop/SettersTrait.php';

require_once 'classes/sketchings/oop/UserInterface.php';

require_once 'classes/sketchings/oop/User.php';

require_once ‘classes/Developer.php';
//Order is critical
$guest = new Developer(); //global namespace

echo $guest->getSalutation();
QUESTIONS
PART 4: Autoloading
Autoloading: index.php
<?php

// Add your class directory to include path

set_include_path('classes/');
// Use default autoload implementation

spl_autoload_register();
$guest = new Developer(); //global namespace

echo $guest->getSalutation();
PART 5: Exceptions
Exception Hierarchy
Exception implements Throwable
…
Error implements Throwable
TypeError extends Error
ParseError extends Error
ArithmeticError extends Error
DivisionByZeroError extends ArithmeticError
AssertionError extends Error
Catching Exceptions
try {

   // Code that may throw an Exception or Error. 

} catch (DivisionByZeroError $e) {

   // Executed only in PHP 7 for DivisionByZeroError

} catch (Throwable $e) {

   // Executed only in PHP 7, will not match in PHP 5

} catch (Exception $e) {

   // Executed only in PHP 5, will not be reached in PHP 7

}
Custom Exception Handler
function exception_handler($e)
{
echo "Uncaught exception: ", $e->getMessage(), "n";
}
set_exception_handler('exception_handler');
Error to Exception
function exception_error_handler($severity, $message, $file, $line) {

if (!(error_reporting() & $severity)) {

// This error code is not included in error_reporting

return;

}

throw new ErrorException($message);//$message, 0, $severity, $file, $line);

}
set_error_handler("exception_error_handler");
Resources
Mastering Object-Oriented PHP by Brandon Savage
LeanPub: The Essentials of Object Oriented PHP
Head First Object-Oriented Analysis and Design
PHP the Right Way
Alena Holligan
• Wife, and Mother of 3 young children
• PHP Teacher at Treehouse
• Portland PHP User Group Leader
• Cascadia PHP Conference (cascadiaphp.com)
@alenaholligan alena@holligan.us https://joind.in/talk/8b9ca

Contenu connexe

Tendances

Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Fabien Potencier
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixturesBill Chang
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICKonstantin Kudryashov
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needKacper Gunia
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)brockboland
 
Data::FormValidator Simplified
Data::FormValidator SimplifiedData::FormValidator Simplified
Data::FormValidator SimplifiedFred Moyer
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLIDJulio Martinez
 

Tendances (20)

Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
Data::FormValidator Simplified
Data::FormValidator SimplifiedData::FormValidator Simplified
Data::FormValidator Simplified
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 

Similaire à Object Features

Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Alena Holligan
 
Lecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxLecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxDavidLazar17
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 
PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Alena Holligan
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Pim Elshoff "Technically DDD"
Pim Elshoff "Technically DDD"Pim Elshoff "Technically DDD"
Pim Elshoff "Technically DDD"Fwdays
 
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 OOPWildan Maulana
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
psnreddy php-oops
psnreddy  php-oopspsnreddy  php-oops
psnreddy php-oopssatya552
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Fwdays
 

Similaire à Object Features (20)

Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
PHP OOP
PHP OOPPHP OOP
PHP OOP
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
Lecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxLecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptx
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 
Value objects
Value objectsValue objects
Value objects
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Pim Elshoff "Technically DDD"
Pim Elshoff "Technically DDD"Pim Elshoff "Technically DDD"
Pim Elshoff "Technically DDD"
 
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
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
psnreddy php-oops
psnreddy  php-oopspsnreddy  php-oops
psnreddy php-oops
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"
 

Plus de Alena Holligan

2023 Longhorn PHP - Learn to Succeed .pdf
2023 Longhorn PHP - Learn to Succeed .pdf2023 Longhorn PHP - Learn to Succeed .pdf
2023 Longhorn PHP - Learn to Succeed .pdfAlena Holligan
 
Environmental variables
Environmental variablesEnvironmental variables
Environmental variablesAlena Holligan
 
Experiential Project Design
Experiential Project DesignExperiential Project Design
Experiential Project DesignAlena Holligan
 
Organization Patterns: MVC
Organization Patterns: MVCOrganization Patterns: MVC
Organization Patterns: MVCAlena Holligan
 
When & Why: Interfaces, abstract classes, traits
When & Why: Interfaces, abstract classes, traitsWhen & Why: Interfaces, abstract classes, traits
When & Why: Interfaces, abstract classes, traitsAlena Holligan
 
Obect-Oriented Collaboration
Obect-Oriented CollaborationObect-Oriented Collaboration
Obect-Oriented CollaborationAlena Holligan
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Exploiting the Brain for Fun and Profit
Exploiting the Brain for Fun and ProfitExploiting the Brain for Fun and Profit
Exploiting the Brain for Fun and ProfitAlena Holligan
 
Environmental Variables
Environmental VariablesEnvironmental Variables
Environmental VariablesAlena Holligan
 
Exploiting the Brain for Fun & Profit #zendcon2016
Exploiting the Brain for Fun & Profit #zendcon2016Exploiting the Brain for Fun & Profit #zendcon2016
Exploiting the Brain for Fun & Profit #zendcon2016Alena Holligan
 
Presentation Bulgaria PHP
Presentation Bulgaria PHPPresentation Bulgaria PHP
Presentation Bulgaria PHPAlena Holligan
 
Exploiting the Brain for Fun and Profit - Lone Star 2016
Exploiting the Brain for Fun and Profit - Lone Star 2016Exploiting the Brain for Fun and Profit - Lone Star 2016
Exploiting the Brain for Fun and Profit - Lone Star 2016Alena Holligan
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 

Plus de Alena Holligan (20)

2023 Longhorn PHP - Learn to Succeed .pdf
2023 Longhorn PHP - Learn to Succeed .pdf2023 Longhorn PHP - Learn to Succeed .pdf
2023 Longhorn PHP - Learn to Succeed .pdf
 
Environmental variables
Environmental variablesEnvironmental variables
Environmental variables
 
Dev parent
Dev parentDev parent
Dev parent
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Dependency Management
Dependency ManagementDependency Management
Dependency Management
 
Experiential Project Design
Experiential Project DesignExperiential Project Design
Experiential Project Design
 
Reduce Reuse Refactor
Reduce Reuse RefactorReduce Reuse Refactor
Reduce Reuse Refactor
 
Organization Patterns: MVC
Organization Patterns: MVCOrganization Patterns: MVC
Organization Patterns: MVC
 
When & Why: Interfaces, abstract classes, traits
When & Why: Interfaces, abstract classes, traitsWhen & Why: Interfaces, abstract classes, traits
When & Why: Interfaces, abstract classes, traits
 
Obect-Oriented Collaboration
Obect-Oriented CollaborationObect-Oriented Collaboration
Obect-Oriented Collaboration
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Let's Talk Scope
Let's Talk ScopeLet's Talk Scope
Let's Talk Scope
 
Exploiting the Brain for Fun and Profit
Exploiting the Brain for Fun and ProfitExploiting the Brain for Fun and Profit
Exploiting the Brain for Fun and Profit
 
Environmental Variables
Environmental VariablesEnvironmental Variables
Environmental Variables
 
Learn to succeed
Learn to succeedLearn to succeed
Learn to succeed
 
Exploiting the Brain for Fun & Profit #zendcon2016
Exploiting the Brain for Fun & Profit #zendcon2016Exploiting the Brain for Fun & Profit #zendcon2016
Exploiting the Brain for Fun & Profit #zendcon2016
 
Presentation Bulgaria PHP
Presentation Bulgaria PHPPresentation Bulgaria PHP
Presentation Bulgaria PHP
 
Presentation pnwphp
Presentation pnwphpPresentation pnwphp
Presentation pnwphp
 
Exploiting the Brain for Fun and Profit - Lone Star 2016
Exploiting the Brain for Fun and Profit - Lone Star 2016Exploiting the Brain for Fun and Profit - Lone Star 2016
Exploiting the Brain for Fun and Profit - Lone Star 2016
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 

Dernier

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Dernier (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Object Features

  • 1. Object Features 1. Access Control 2. Managing Types 3. Namespacing and Autoloading 4. Exceptions
  • 2. PART 1: Access Control Scope Visibility: Public, Private, Protected State: Static, Final Magic
  • 6. Visibility 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 Children can be more restrictive but NOT less restrictive
  • 7. class User {
 public $lang = "en"; //public
 private $name = “Guest"; //private
 protected $greeting = [ ‘en’ => “Welcome”, ‘sp’ => “Hola” ]; //protected
 public function getSalutation($lang = null) { //polymorphic method
 $lang = $this->getLang($lang); //abstracting
 return $this->greeting[$lang] . " " . $this->name;
 }
 protected function getLanguage($lang) { //reuse
 if (!array_key_exists($lang, $this->greeting)) $lang = $this->lang;
 return $lang;
 }
 public function setName($name) { //setter
 $this->name = ucwords($name); //control formatting
 }
 public function getName() { //getter
 return $this->name; //can access private
 }
 }
  • 8. Accessing Visibility $guest = new User();
 echo $guest->getSalutation();
 //$guest->name = "alena"; //private not accessible
 $guest->setName("alena");
 //$guest->greeting = "Hello";//protected not accessible
 echo $guest->getSalutation(‘sp’);
 echo "Hello " . $guest->getName(); When the script is run, it will return: Welcome GuestHola AlenaHello Alena
  • 9. Accessed by a child class class Developer extends User {
 public $name = "Programmer";//new property
 protected $greeting = "Hello";//overridable, not private
 //override method
 public function getSalutation($lang = null) {//same params
 return $this->greeting //protected child string
 ." ".$this->getName() //private parent
 .", Developer";
 }
 ...
 }
  • 10. Accessing Child Visibility $developer = new Developer();
 echo $developer->name;//child $name
 $developer->name = "tiberias";//child $name
 echo $developer->name;//child $name
 echo $developer->getName();//parent $name
 //ProgrammertiberiasGuest echo $developer->getSalutation();//child $greeting, parent $name
 //Hello Guest, Developer $developer->setName("alena");//parent $name
 echo $developer->name;//child $name
 echo $developer->getName();//parent $name
 //tiberiasAlena echo $developer->getSalutation();//child $greeting, parent $name
 //Hello Alena, Developer
  • 12. State Static Do not need to instantiate an object Static methods must be public Internal Access: self::, parent::, static:: Late static bindings: class that’s calling Final Methods cannot be overridden Class cannot be extended
  • 13. class User { ... protected static $encouragements = array(
 "You are beautiful!",
 "You have this!"
 );
 
 final public static function encourage() { 
 //Late Static Bindings, class that’s calling
 $int = rand(1, count(static::$encouragements));
 return static::$encouragements[$int-1];
 }
 }
  • 14. final class Developer extends User {
 ...
 private static $encouragements = array(
 "You are not your code",
 "There has never been perfect software"
 );
 
 public static function encourage() { 
 //error parent was final
 }
 public static function devEncourage() {
 $int = rand(1, count(self::$encouragements));
 return self::$encouragements[$int-1];
 }
 public static function userEncourage() {
 $int = rand(1, count(parent::$encouragements));
 return parent::$encouragements[$int-1];
 }
 }
  • 15. Calling State //echo User::$encouragements[0];//Error protected
 echo Developer::$encouragements[0];
 echo User::encourage();//User (static::)
 echo Developer::encourage();//Developer (static::)
 echo Developer::devEncourage();//Developer (self::)
 echo Developer::userEncourage();//User (parent::)
 class Architect extends Developer {
 //Error: Developer is final
 } When the script is run, it will return:
 You are beautiful!You are beautiful!You are not your code!There has never been perfect software.You have this!
  • 16. class Developer extends User {
 ...
 //must match array type of parent
 protected $greeting = [ ‘en’ => “Hello”, ‘sp’ => “Hola” ];
 public function getSalutation($lang = ‘en’) { //extended
 $salutation = parent::getSaluation($lang); //not a static call
 return $salutation . ", Developer";
 }
 } $developer = new Developer();
 $developer->setName("alena");
 echo $developer->getSalutation(); When the script is run, it will return: Hello Alena, Developer
  • 19. 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
  • 20. Magic Constants Predefined constants in PHP For more see http://php.net/manual/en/ language.constants.predefined.php
  • 21. Using Magic Methods and Constants class User { ...
 
 public function __construct($name) {
 $this->setName($name);
 }
 
 public function __toString() {
 return __CLASS__. “: “
 . $this->getSalutation();
 }
 ...
 }
  • 22. Invoking the Magic $alena = new User("alena");
 echo $alena; $tiberias = new Developer("tiberias");
 echo $tiberias; When the script is run, it will return: User: Welcome Alena
 Developer: Welcome Tiberias, Developer
  • 23. Magic Setter Trait trait SettersTrait {
 public function __set($name, $value) { //magic method
 $setter = 'set'.$name; //creating method name
 if (method_exists($this, $setter)) {
 $this->$setter($value); //variable function or method
 //$this->{‘set’.$name}; //optionally use curly braces
 } else {
 $this->$name = $value; //variable variable or property 
 }
 }
 }
  • 25. PART 2: Managing Types Type Declarations (Hints) Return Types Type Juggling Strict Types
  • 26. class User {
 …
 public function getSalutation(string $lang = null) { //accept string, null or nothing
 $lang = $this->getLang($lang);
 return $this->greeting[$lang] . " " . $this->name;
 }
 public function getLanguage(?string $lang) { //accept string or null
 if (!array_key_exists($lang, $this->greeting)) $lang = $this->lang;
 return $lang;
 }
 public function setName(string $name) { //accept string only
 $this->name = ucwords($name);
 }
 public function setName(string $name) {//accept string only
 $this->name = ucwords($name);
 }
 public function getName() {
 return $this->name;
 }
 public function setGreeting(array $greeting){ //accept array only
 $this->greeting = $greeting;
 }
 }
  • 27. class User {
 …
 public function getSalutation(string $lang = null): string { //return string
 $lang = $this->getLang($lang);
 return $this->greeting[$lang] . " " . $this->name;
 }
 public function getLanguage(?string $lang): ?string { //return string or null
 if (!array_key_exists($lang, $this->greeting)) $lang = $this->lang;
 return $lang;
 }
 public function setName(string $name): void { //no return
 $this->name = ucwords($name);
 return; //this is void as well
 }
 public function setName(string $name): void {//no return
 $this->name = ucwords($name);
 }
 public function getName(): string {
 return $this->name;
 }
 public function setGreeting(array $greeting): void { //no return
 $this->greeting = $greeting;
 }
 }
  • 28. Type Juggling //By default, scalar type-declarations are non-strict class User {
 …
 public function setName(string $name): void { //will attempt to convert to string
 $this->name = ucwords($name);
 }
 } $guest = new User(1);
 var_dump($guest->getName());
 // string(1) "1"
  • 29. Type Juggling //By default, scalar type-declarations are non-strict class User {
 …
 public function getName(): string {
 return 2; // will convert to return string
 }
 } $guest = new User(1);
 var_dump($guest->getName());
 // string(1) “2"
  • 30. Type Juggling //By default, scalar type-declarations are non-strict class User {
 …
 public function setGreeting(array $greeting): void { //getter
 $this->greeting = $greeting; //can access private
 }
 } $guest = new User(1);
 $guest->setGreeting("Greetings");
 // TypeError: Argument 1 passed to User::setGreeting() must be of the type array, string given
  • 31. Strict Types declare(strict_types=1); class User {
 …
 public function setName(string $name): void { //MUST pass string
 $this->name = ucwords($name);
 }
 } $guest = new User(1);
 //TypeError: Argument 1 passed to User::setName() must be of the type string, integer given
  • 32. Strict Types declare(strict_types=1); class User {
 …
 public function getName(): string { //MUST return type string
 return 2; //attempt int
 }
 } $guest = new User();
 $guest->getName();
 //TypeError: Return value of User::getName() must be of the type string, integer returned
  • 35.
  • 36. Namespacing SHOULD Separate files for each class, interface, and trait Add to the top of each file 
 namespace sketchingsoop; When calling a class file link to full path or ‘use’ path Default namespace is current namespace No namespace is global namespace ‘’
  • 38. Setting Namespaces //classes/sketchings/oop/User.php: namespace referencing same namespace
 namespace sketchingsoop;
 class User implements UserInterface {…} //classes/Developer.php: OPTION 1 use path
 use sketchingsoopUser;
 class Developer extends User {…} //classes/Developer.php: OPTION 2 full path
 class Developer extends sketchingsoopUser {…}
  • 39. Using Namespaces: index.php <?php
 require_once 'classes/sketchings/oop/SettersTrait.php';
 require_once 'classes/sketchings/oop/UserInterface.php';
 require_once 'classes/sketchings/oop/User.php';
 require_once ‘classes/Developer.php'; //Order is critical $guest = new Developer(); //global namespace
 echo $guest->getSalutation();
  • 42. Autoloading: index.php <?php
 // Add your class directory to include path
 set_include_path('classes/'); // Use default autoload implementation
 spl_autoload_register(); $guest = new Developer(); //global namespace
 echo $guest->getSalutation();
  • 44. Exception Hierarchy Exception implements Throwable … Error implements Throwable TypeError extends Error ParseError extends Error ArithmeticError extends Error DivisionByZeroError extends ArithmeticError AssertionError extends Error
  • 45. Catching Exceptions try {
    // Code that may throw an Exception or Error. 
 } catch (DivisionByZeroError $e) {
    // Executed only in PHP 7 for DivisionByZeroError
 } catch (Throwable $e) {
    // Executed only in PHP 7, will not match in PHP 5
 } catch (Exception $e) {
    // Executed only in PHP 5, will not be reached in PHP 7
 }
  • 46. Custom Exception Handler function exception_handler($e) { echo "Uncaught exception: ", $e->getMessage(), "n"; } set_exception_handler('exception_handler');
  • 47. Error to Exception function exception_error_handler($severity, $message, $file, $line) {
 if (!(error_reporting() & $severity)) {
 // This error code is not included in error_reporting
 return;
 }
 throw new ErrorException($message);//$message, 0, $severity, $file, $line);
 } set_error_handler("exception_error_handler");
  • 48. Resources Mastering Object-Oriented PHP by Brandon Savage LeanPub: The Essentials of Object Oriented PHP Head First Object-Oriented Analysis and Design PHP the Right Way
  • 49. Alena Holligan • Wife, and Mother of 3 young children • PHP Teacher at Treehouse • Portland PHP User Group Leader • Cascadia PHP Conference (cascadiaphp.com) @alenaholligan alena@holligan.us https://joind.in/talk/8b9ca