SlideShare a Scribd company logo
PHP7 Anonymous Classes:
Behind the Mask
PHP7 Anonymous Classes
• What is an Anonymous Class?
• A class that is defined “inline”, within user code, at runtime
• Sometimes called “inline” or “nested” classes
• Don’t have the scope of the class where they are created
• Not assigned a class name
PHP7 Anonymous Classes
• What is an Anonymous Class?
• How do I use an Anonymous Class?
PHP7 Anonymous Classes
• How do I use an Anonymous Class?
• No name given to the class (internally assigned by PHP)
• Closing semi-colon (;)
• Constructor arguments passed in class definition
• All objects created by the same anonymous class declaration are instances of
that class (the internal class reference is identical).
$objectInstance = new class( 'arguments'... ) {
// defined properties and methods
};
PHP7 Anonymous Classes
function locationFormatBuilder (array $location = []) {
return new class (...$location) {
const POINT_MASK = '% 3d° % 2d' %5.2f" %s';
public function __construct($latitude, $longitude) {
$this->latitude = $latitude;
$this->longitude = $longitude;
}
protected function point($point, $orientation) {
…
return vsprintf(self::POINT_MASK, [$degrees, $minutes, $seconds, $direction]);
}
public function __toString() {
return vsprintf(
'%s, %s',
[$this->point($this->latitude, ['N','S']), $this->point($this->longitude, ['E','W'])]
);
}
};
}
PHP7 Anonymous Classes
$locations = [
[ 51.5074, -0.1278 ], // London
[ 40.7128, -74.0059 ], // New York
[ -22.9068, -43.1729 ], // Rio de Janeiro
[ -33.9249, 18.4241 ], // Cape Town
[ 19.0760, 72.8777 ], // Mumbai
[ 35.6895, 139.6917 ], // Tokyo
[ -33.8688, 151.2093 ], // Sydney
[ 31.7683, 35.2137 ], // Jerusalem
];
foreach ($locations as $location) {
echo locationFormatBuilder($location), PHP_EOL;
}
51° 30' 26.00" N, 0° 7' 40.00" W
40° 42' 46.00" N, 74° 0' 21.00" W
22° 54' 24.00" S, 43° 10' 22.00" W
33° 55' 29.00" S, 18° 25' 26.00" E
19° 4' 33.00" N, 72° 52' 39.00" E
35° 41' 22.00" N, 139° 41' 30.00" E
33° 52' 7.00" S, 151° 12' 33.00" E
31° 46' 5.00" N, 35° 12' 49.00" E
PHP7 Anonymous Classes
PHP7 Anonymous Classes
• How do I use an Anonymous Class?
• Can “implement” and “extend”
• Can use Traits
$objectInstance = new class( 'arguments'... ) {
// defined properties and methods
};
PHP7 Anonymous Classes
• Anonymous Class Factories
• Builds an Anonymous Class that extends the “userModel” class with optional
Traits
• Uses “eval()”
$anonymousModel = (new AnonymousClassFactory('userModel'))
->withConstructorArguments($databaseConnection)
->withTraits('softDelete', 'auditable')
->create();
PHP7 Anonymous Classes
trait softDelete {
protected $softDelete = true;
}
trait auditable {
protected $auditable = true;
}
class userModel {
protected $dbConnection;
protected $loggingEnabled;
public function __construct($dbConnection, $loggingEnabled = false) {
$this->dbConnection = $dbConnection;
$this->loggingEnabled = $loggingEnabled;
}
}
PHP7 Anonymous Classes
$dbConnection = new PDO('sqlite:example.db');
$loggingEnabled = true;
$className = 'userModel';
$traits = implode(', ', ['softDelete', 'auditable']);
$classDefinition = <<<ANONYMOUS
new class($dbConnection, $loggingEnabled) extends {$className} {
use {$traits};
};
ANONYMOUS;
$anonymousUserModelClassInstance = eval("return $classDefinition;");
PHP7 Anonymous Classes
object(class@anonymous)#2 (4) {
["dbConnection":protected]=>
object(PDO)#1 (0) {
}
["loggingEnabled":protected]=>
bool(true)
["softDelete":protected]=>
bool(true)
["auditable":protected]=>
bool(true)
}
PHP7 Anonymous Classes
• Anonymous Class Factories
• In Search of an Anonymous Class Factory
https://markbakeruk.net/2016/05/03/in-search-of-an-anonymous-class-factory/
• Anonymous Class Factory – The Results are in
https://markbakeruk.net/2016/05/12/anonymous-class-factory-the-results-are-in/
$anonymousModel = (new AnonymousClassFactory('modelClass'))
->withConstructorArguments($databaseConnection)
->withTraits('softDelete', 'auditable')
->create();
PHP7 Anonymous Classes
class userController {
protected $user;
public function __construct(userModel $user) {
$this->user = $user;
}
}
$controller = new UserController($anonymousUserModelClassInstance);
PHP7 Anonymous Classes
• What is an Anonymous Class?
• How do I use an Anonymous Class?
• What Limitations are there to Anonymous Classes?
PHP7 Anonymous Classes
• What Limitations are there to Anonymous Classes?
• Definition and Instantiation in a Single Step
• Cannot be Serialized
• Effectively Final
• No OpCaching
• No Documentation (DocBlocks)
• No IDE Hinting
PHP7 Anonymous Classes
• What is an Anonymous Class?
• How do I use an Anonymous Class?
• What Limitations are there to Anonymous Classes?
• Why would I use Anonymous Classes?
PHP7 Anonymous Classes
• Why would I use Anonymous Classes?
• One-off Objects
• Private Classes
• Test Mocking
• On-demand Typed Structures (instead of generic arrays or StdClass)
• Ad-hoc adapters in a loosely coupled architecture
• To bypass Autoloading
PHP7 Anonymous Classes
• Why would I use Anonymous Classes?
• Test Mocking
• https://mfyu.co.uk/post/anonymous-classes-in-php-7-are-fantastic-for-tests
PHP7 Anonymous Classes
• Inner- or Nested-Classes
class SpyMaster {
private $targetObject;
protected $objectMission;
public function __construct($targetObject) {
$this->targetObject = $targetObject;
$this->objectMission = new SpyObjectMission($targetObject);
}
protected function getHandler() {
…
}
public function infiltrate() {
return $this->getHandler();
}
}
PHP7 Anonymous Classes
• Inner- or Nested-Classes
class SpyObjectMission {
public $methods = [];
public $invoker;
public function __construct($targetObject) {
$reflector = new ReflectionObject($targetObject);
$this->invoker = $this->getInvoker($reflector, $targetObject);
}
protected function getInvoker(ReflectionObject $reflector, $targetObject) {
$staticMethods = array_column($reflector->getMethods(ReflectionMethod::IS_STATIC), 'name’);
$this->methods = array_diff(
array_column($reflector->getMethods(), 'name’), $staticMethods)
);
$invoker = function($methodName, ...$args) {
return self::$methodName(...$args);
};
return $invoker->bindTo($targetObject, get_class($targetObject));
}
}
PHP7 Anonymous Classes
• Inner- or Nested-Classes
protected function getHandler() {
return new class ($this->objectMission, $this->staticMission) {
private $objectMission;
public function __construct(SpyObjectMission $objectMission) {
$this->objectMission = $objectMission;
}
public function __call($methodName, $args) {
if (in_array($methodName, $this->objectMission->methods)) {
$invoker = $this->objectMission->invoker;
return $invoker($methodName, ...$args);
}
throw new Exception("Object Method {$methodName} does not exist");
}
};
}
PHP7 Anonymous Classes
• Inner- or Nested-Classes
$test = new classThatWeWantToTest(1, 2, 3);
$spy = (new SpyMaster($test))
->infiltrate();
echo 'SPY FOR TEST #1', PHP_EOL;
echo $spy->privateMethodThatWeWantToTest(), PHP_EOL;
PHP7 Anonymous Classes
• Inner- or Nested-Classes
• Closures, Anonymous Classes and an alternative approach to Test Mocking
(Part 2)
• https://markbakeruk.net/2017/07/30/closures-anonymous-classes-and-an-alternative-
approach-to-test-mocking-part-2/
• Closures, Anonymous Classes and an alternative approach to Test Mocking
(Part 4)
• https://markbakeruk.net/2018/01/23/closures-anonymous-classes-and-an-alternative-
approach-to-test-mocking-part-4/
PHP7 Anonymous Classes
Phpanpy
Mock object framework for unit testing
Like Mockery https://packagist.org/packages/mockery/mockery
PHP7 Anonymous Classes
$dummyConstructorArguments = [1,2];
$points = (new PhpanpyAnonymousDoubleFactory('GeodeticLatLong', ...$dummyConstructorArguments))
->setMethodReturnValuesList([
'getLatitude' => [51.5074, 40.7128, -22.9068, -33.9249, 19.0760, 35.6895, -33.8688, 31.7683],
'getLongitude' => [-0.1278, -74.0059, -43.1729, 18.4241, 72.8777, 139.6917, 151.2093, 35.2137],
])->setMethodReturnValuesFixed([
'getElevation' => 0.0
])->create();
$line = (new PhpanpyAnonymousDoubleFactory('GeodeticLine’))
->suppressOriginalConstructor()
->setMethodReturnValuesFixed([
'getNextPoint' => $points
])->create();
PHP7 Anonymous Classes
try {
for($i = 0; $i < 10; ++$i) {
$point = $line->getNextPoint();
echo sprintf(
"%+ 9.4f %+ 9.4f % 7.4f",
$point->getLatitude(), $point->getLongitude(), $point->getElevation()
), PHP_EOL;
}
} catch (Exception $e) {
echo $e->getMessage();
}
PHP7 Anonymous Classes
new class(...$this->constructorArgs) extends GeodeticLatLong {
use PhpanpyAnonymousPrePostHooks, PhpanpylistReturnValuesTrait, PhpanpyfixedReturnValueTrait;
public function __construct ($latitude, $longitude, $elevation = 0) {
$args = func_get_args();
$this->firePreHookInstance(__FUNCTION__, ...$args);
parent::__construct($latitude, $longitude, $elevation);
$this->firePostHookInstance(__FUNCTION__, ...$args);
}
public function getLatitude ($radians = false) {
$args = func_get_args();
$this->firePreHookInstance(__FUNCTION__, ...$args);
$result = $this->traitMethodCallReturnNextValueFromList(__FUNCTION__);
$this->firePostHookInstance(__FUNCTION__, $result, ...$args);
return $result;
}
public function getElevation () {
$args = func_get_args();
$this->firePreHookInstance(__FUNCTION__, ...$args);
$result = $this->traitMethodCallReturnFixedValue(__FUNCTION__);
$this->firePostHookInstance(__FUNCTION__, $result, ...$args);
return $result;
}
}
Anonymous Classes: Behind the Mask

More Related Content

What's hot

Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
Chhom Karath
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
Alena Holligan
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
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
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
Alena Holligan
 
Best Guide for Javascript Objects
Best Guide for Javascript ObjectsBest Guide for Javascript Objects
Best Guide for Javascript Objects
Muhammad khurram khan
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
04inherit
04inherit04inherit
04inherit
Waheed Warraich
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
Aleksander Fabijan
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
Mindfire Solutions
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
Sven Efftinge
 
Hibernate Inheritenc Mapping
Hibernate Inheritenc MappingHibernate Inheritenc Mapping
Hibernate Inheritenc Mapping
javafasttrack
 

What's hot (20)

Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
core java
core javacore java
core java
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
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
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Best Guide for Javascript Objects
Best Guide for Javascript ObjectsBest Guide for Javascript Objects
Best Guide for Javascript Objects
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
04inherit
04inherit04inherit
04inherit
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
Hibernate Inheritenc Mapping
Hibernate Inheritenc MappingHibernate Inheritenc Mapping
Hibernate Inheritenc Mapping
 

Similar to Anonymous Classes: Behind the Mask

Only oop
Only oopOnly oop
Only oop
anitarooge
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
Alena Holligan
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
Alena Holligan
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
rani marri
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?
Sam Thomas
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
switipatel4
 
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
Alena Holligan
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHP
Alena Holligan
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
Alena Holligan
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
Alena Holligan
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find Useful
David Engel
 

Similar to Anonymous Classes: Behind the Mask (20)

Only oop
Only oopOnly oop
Only oop
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
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
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHP
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find Useful
 

More from Mark Baker

Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
Mark Baker
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
Mark Baker
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
Mark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
Mark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
Mark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
Mark Baker
 
A Brief History of Elephpants
A Brief History of ElephpantsA Brief History of Elephpants
A Brief History of Elephpants
Mark Baker
 
Aspects of love slideshare
Aspects of love slideshareAspects of love slideshare
Aspects of love slideshare
Mark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
Mark Baker
 
A Brief History of ElePHPants
A Brief History of ElePHPantsA Brief History of ElePHPants
A Brief History of ElePHPants
Mark Baker
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
Mark Baker
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
Mark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
Mark Baker
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
Mark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
Mark Baker
 
Giving birth to an ElePHPant
Giving birth to an ElePHPantGiving birth to an ElePHPant
Giving birth to an ElePHPant
Mark Baker
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
Mark Baker
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensions
Mark Baker
 

More from Mark Baker (20)

Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
A Brief History of Elephpants
A Brief History of ElephpantsA Brief History of Elephpants
A Brief History of Elephpants
 
Aspects of love slideshare
Aspects of love slideshareAspects of love slideshare
Aspects of love slideshare
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
A Brief History of ElePHPants
A Brief History of ElePHPantsA Brief History of ElePHPants
A Brief History of ElePHPants
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
Giving birth to an ElePHPant
Giving birth to an ElePHPantGiving birth to an ElePHPant
Giving birth to an ElePHPant
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensions
 

Recently uploaded

Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 

Recently uploaded (20)

Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 

Anonymous Classes: Behind the Mask

  • 2. PHP7 Anonymous Classes • What is an Anonymous Class? • A class that is defined “inline”, within user code, at runtime • Sometimes called “inline” or “nested” classes • Don’t have the scope of the class where they are created • Not assigned a class name
  • 3. PHP7 Anonymous Classes • What is an Anonymous Class? • How do I use an Anonymous Class?
  • 4. PHP7 Anonymous Classes • How do I use an Anonymous Class? • No name given to the class (internally assigned by PHP) • Closing semi-colon (;) • Constructor arguments passed in class definition • All objects created by the same anonymous class declaration are instances of that class (the internal class reference is identical). $objectInstance = new class( 'arguments'... ) { // defined properties and methods };
  • 5. PHP7 Anonymous Classes function locationFormatBuilder (array $location = []) { return new class (...$location) { const POINT_MASK = '% 3d° % 2d' %5.2f" %s'; public function __construct($latitude, $longitude) { $this->latitude = $latitude; $this->longitude = $longitude; } protected function point($point, $orientation) { … return vsprintf(self::POINT_MASK, [$degrees, $minutes, $seconds, $direction]); } public function __toString() { return vsprintf( '%s, %s', [$this->point($this->latitude, ['N','S']), $this->point($this->longitude, ['E','W'])] ); } }; }
  • 6. PHP7 Anonymous Classes $locations = [ [ 51.5074, -0.1278 ], // London [ 40.7128, -74.0059 ], // New York [ -22.9068, -43.1729 ], // Rio de Janeiro [ -33.9249, 18.4241 ], // Cape Town [ 19.0760, 72.8777 ], // Mumbai [ 35.6895, 139.6917 ], // Tokyo [ -33.8688, 151.2093 ], // Sydney [ 31.7683, 35.2137 ], // Jerusalem ]; foreach ($locations as $location) { echo locationFormatBuilder($location), PHP_EOL; }
  • 7. 51° 30' 26.00" N, 0° 7' 40.00" W 40° 42' 46.00" N, 74° 0' 21.00" W 22° 54' 24.00" S, 43° 10' 22.00" W 33° 55' 29.00" S, 18° 25' 26.00" E 19° 4' 33.00" N, 72° 52' 39.00" E 35° 41' 22.00" N, 139° 41' 30.00" E 33° 52' 7.00" S, 151° 12' 33.00" E 31° 46' 5.00" N, 35° 12' 49.00" E PHP7 Anonymous Classes
  • 8. PHP7 Anonymous Classes • How do I use an Anonymous Class? • Can “implement” and “extend” • Can use Traits $objectInstance = new class( 'arguments'... ) { // defined properties and methods };
  • 9. PHP7 Anonymous Classes • Anonymous Class Factories • Builds an Anonymous Class that extends the “userModel” class with optional Traits • Uses “eval()” $anonymousModel = (new AnonymousClassFactory('userModel')) ->withConstructorArguments($databaseConnection) ->withTraits('softDelete', 'auditable') ->create();
  • 10. PHP7 Anonymous Classes trait softDelete { protected $softDelete = true; } trait auditable { protected $auditable = true; } class userModel { protected $dbConnection; protected $loggingEnabled; public function __construct($dbConnection, $loggingEnabled = false) { $this->dbConnection = $dbConnection; $this->loggingEnabled = $loggingEnabled; } }
  • 11. PHP7 Anonymous Classes $dbConnection = new PDO('sqlite:example.db'); $loggingEnabled = true; $className = 'userModel'; $traits = implode(', ', ['softDelete', 'auditable']); $classDefinition = <<<ANONYMOUS new class($dbConnection, $loggingEnabled) extends {$className} { use {$traits}; }; ANONYMOUS; $anonymousUserModelClassInstance = eval("return $classDefinition;");
  • 12. PHP7 Anonymous Classes object(class@anonymous)#2 (4) { ["dbConnection":protected]=> object(PDO)#1 (0) { } ["loggingEnabled":protected]=> bool(true) ["softDelete":protected]=> bool(true) ["auditable":protected]=> bool(true) }
  • 13. PHP7 Anonymous Classes • Anonymous Class Factories • In Search of an Anonymous Class Factory https://markbakeruk.net/2016/05/03/in-search-of-an-anonymous-class-factory/ • Anonymous Class Factory – The Results are in https://markbakeruk.net/2016/05/12/anonymous-class-factory-the-results-are-in/ $anonymousModel = (new AnonymousClassFactory('modelClass')) ->withConstructorArguments($databaseConnection) ->withTraits('softDelete', 'auditable') ->create();
  • 14. PHP7 Anonymous Classes class userController { protected $user; public function __construct(userModel $user) { $this->user = $user; } } $controller = new UserController($anonymousUserModelClassInstance);
  • 15. PHP7 Anonymous Classes • What is an Anonymous Class? • How do I use an Anonymous Class? • What Limitations are there to Anonymous Classes?
  • 16. PHP7 Anonymous Classes • What Limitations are there to Anonymous Classes? • Definition and Instantiation in a Single Step • Cannot be Serialized • Effectively Final • No OpCaching • No Documentation (DocBlocks) • No IDE Hinting
  • 17. PHP7 Anonymous Classes • What is an Anonymous Class? • How do I use an Anonymous Class? • What Limitations are there to Anonymous Classes? • Why would I use Anonymous Classes?
  • 18. PHP7 Anonymous Classes • Why would I use Anonymous Classes? • One-off Objects • Private Classes • Test Mocking • On-demand Typed Structures (instead of generic arrays or StdClass) • Ad-hoc adapters in a loosely coupled architecture • To bypass Autoloading
  • 19. PHP7 Anonymous Classes • Why would I use Anonymous Classes? • Test Mocking • https://mfyu.co.uk/post/anonymous-classes-in-php-7-are-fantastic-for-tests
  • 20. PHP7 Anonymous Classes • Inner- or Nested-Classes class SpyMaster { private $targetObject; protected $objectMission; public function __construct($targetObject) { $this->targetObject = $targetObject; $this->objectMission = new SpyObjectMission($targetObject); } protected function getHandler() { … } public function infiltrate() { return $this->getHandler(); } }
  • 21. PHP7 Anonymous Classes • Inner- or Nested-Classes class SpyObjectMission { public $methods = []; public $invoker; public function __construct($targetObject) { $reflector = new ReflectionObject($targetObject); $this->invoker = $this->getInvoker($reflector, $targetObject); } protected function getInvoker(ReflectionObject $reflector, $targetObject) { $staticMethods = array_column($reflector->getMethods(ReflectionMethod::IS_STATIC), 'name’); $this->methods = array_diff( array_column($reflector->getMethods(), 'name’), $staticMethods) ); $invoker = function($methodName, ...$args) { return self::$methodName(...$args); }; return $invoker->bindTo($targetObject, get_class($targetObject)); } }
  • 22. PHP7 Anonymous Classes • Inner- or Nested-Classes protected function getHandler() { return new class ($this->objectMission, $this->staticMission) { private $objectMission; public function __construct(SpyObjectMission $objectMission) { $this->objectMission = $objectMission; } public function __call($methodName, $args) { if (in_array($methodName, $this->objectMission->methods)) { $invoker = $this->objectMission->invoker; return $invoker($methodName, ...$args); } throw new Exception("Object Method {$methodName} does not exist"); } }; }
  • 23. PHP7 Anonymous Classes • Inner- or Nested-Classes $test = new classThatWeWantToTest(1, 2, 3); $spy = (new SpyMaster($test)) ->infiltrate(); echo 'SPY FOR TEST #1', PHP_EOL; echo $spy->privateMethodThatWeWantToTest(), PHP_EOL;
  • 24. PHP7 Anonymous Classes • Inner- or Nested-Classes • Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 2) • https://markbakeruk.net/2017/07/30/closures-anonymous-classes-and-an-alternative- approach-to-test-mocking-part-2/ • Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 4) • https://markbakeruk.net/2018/01/23/closures-anonymous-classes-and-an-alternative- approach-to-test-mocking-part-4/
  • 25. PHP7 Anonymous Classes Phpanpy Mock object framework for unit testing Like Mockery https://packagist.org/packages/mockery/mockery
  • 26. PHP7 Anonymous Classes $dummyConstructorArguments = [1,2]; $points = (new PhpanpyAnonymousDoubleFactory('GeodeticLatLong', ...$dummyConstructorArguments)) ->setMethodReturnValuesList([ 'getLatitude' => [51.5074, 40.7128, -22.9068, -33.9249, 19.0760, 35.6895, -33.8688, 31.7683], 'getLongitude' => [-0.1278, -74.0059, -43.1729, 18.4241, 72.8777, 139.6917, 151.2093, 35.2137], ])->setMethodReturnValuesFixed([ 'getElevation' => 0.0 ])->create(); $line = (new PhpanpyAnonymousDoubleFactory('GeodeticLine’)) ->suppressOriginalConstructor() ->setMethodReturnValuesFixed([ 'getNextPoint' => $points ])->create();
  • 27. PHP7 Anonymous Classes try { for($i = 0; $i < 10; ++$i) { $point = $line->getNextPoint(); echo sprintf( "%+ 9.4f %+ 9.4f % 7.4f", $point->getLatitude(), $point->getLongitude(), $point->getElevation() ), PHP_EOL; } } catch (Exception $e) { echo $e->getMessage(); }
  • 28. PHP7 Anonymous Classes new class(...$this->constructorArgs) extends GeodeticLatLong { use PhpanpyAnonymousPrePostHooks, PhpanpylistReturnValuesTrait, PhpanpyfixedReturnValueTrait; public function __construct ($latitude, $longitude, $elevation = 0) { $args = func_get_args(); $this->firePreHookInstance(__FUNCTION__, ...$args); parent::__construct($latitude, $longitude, $elevation); $this->firePostHookInstance(__FUNCTION__, ...$args); } public function getLatitude ($radians = false) { $args = func_get_args(); $this->firePreHookInstance(__FUNCTION__, ...$args); $result = $this->traitMethodCallReturnNextValueFromList(__FUNCTION__); $this->firePostHookInstance(__FUNCTION__, $result, ...$args); return $result; } public function getElevation () { $args = func_get_args(); $this->firePreHookInstance(__FUNCTION__, ...$args); $result = $this->traitMethodCallReturnFixedValue(__FUNCTION__); $this->firePostHookInstance(__FUNCTION__, $result, ...$args); return $result; } }