SlideShare a Scribd company logo
AST + Better Reflection
James Titcumb
PHP Benelux 2016 Unconference
James Titcumb
www.jamestitcumb.com
www.roave.com
www.phphants.co.uk
www.phpsouthcoast.co.uk
@asgrim
Who is this guy?
Reflection
AST + Better Reflection (PHP Benelux 2016 Unconference)
© 1937 Disney’s Snow White - disneyscreencaps.com
AST + Better Reflection (PHP Benelux 2016 Unconference)
● Structure
● Metadata
● Values
● Type introspection
● Modification
Reflection
How does it work?
GET_REFLECTION_OBJECT_PTR(ce);
lc_name = zend_str_tolower_dup(name, name_len);
if ((ce == zend_ce_closure && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1)
&& memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0)
|| zend_hash_str_exists(&ce->function_table, lc_name, name_len)) {
efree(lc_name);
RETURN_TRUE;
} else {
efree(lc_name);
RETURN_FALSE;
}
Okay. What now?
github.com/ /BetterReflection
Better Reflection!
AST + Better Reflection (PHP Benelux 2016 Unconference)
What?
Why?
How?
Magic of the AST
source: http://goo.gl/HORwLQ
WTF is AST?
use PhpParserParserFactory;
$parser = (new ParserFactory)
->create(ParserFactory::PREFER_PHP7);
print_r($parser->parse(
file_get_contents('ast-demo-src.php')
));
<?php
echo "Hello world";
AST
`-- Echo statement
`-- String, value "Hello world"
<?php
echo "Hello " . "world";
AST
`-- Echo statement
`-- Concat
|-- Left
| `-- String, value "Hello "
`-- Right
`-- String, value "world"
AST to Reflection
Benefits?
ReflectionProperty->getDocBlockTypes()
Types!
Using Better Reflection
$reflection = new ReflectionClass(
'BetterReflectionTestFixtureExampleClass'
);
$this->assertSame(
'ExampleClass',
$reflection->getShortName()
);
$reflection = ReflectionClass::createFromName(
'BetterReflectionTestFixtureExampleClass'
);
$this->assertSame(
'ExampleClass',
$reflection->getShortName()
);
// In ReflectionClass :
public static function createFromName($className)
{
return ClassReflector::buildDefaultReflector()->reflect($className);
}
// In ClassReflector :
public static function buildDefaultReflector()
{
return new self(new AggregateSourceLocator([
new PhpInternalSourceLocator(),
new EvaledCodeSourceLocator(),
new AutoloadSourceLocator(),
]));
}
AutoloadSourceLocator
ReflectionClass::createFromName(new MyClass)
replace stream wrapper
disable error handling
call “class_exists”
restore stream wrapper
restore error handling
store attempted filename load
DO NOT LOAD FILE!
return stored filename
Read file and parse AST!
(don’t try this at home kids!)
Some voodoo...
AST + Better Reflection (PHP Benelux 2016 Unconference)
class MyClass
{
public function foo()
{
return 5;
}
}
// Create the reflection first
// ***BEFORE*** class is loaded
$classInfo = ReflectionClass::createFromName('MyClass');
// Override the body...!
$methodInfo = $classInfo->getMethod('foo');
$methodInfo->setBody(function () {
return 4;
});
// Save the class and require it
$classCode = (new CodePrinter())->prettyPrint([$classInfo->getAst()]);
$tmpFile = tempnam(sys_get_temp_dir(), 'br-monkey-patching');
file_put_contents($tmpFile, '<?php ' . $classCode);
require_once($tmpFile);
unlink($tmpFile);
// Now create an instance, and call the function...
$c = new MyClass();
var_dump($c->foo()); // will be 4!!!
AST + Better Reflection (PHP Benelux 2016 Unconference)
What’s in it for me?
The future...
● DONE Currently: rewriting the internals
○ SourceLocators “might” return some code ?!
● DONE Returning AST/Code for method/fn
Ideas/plans - DONE
● WIP More compatibility core reflection
● WIP Reflect core fns with default params
○ This is not currently possible with core reflection
● WIP Modification & exporting
● WIP Reflecting on closures
Ideas/plans - WIP
● Adding a getColumn() function
● PHP 7 compatibility
● @inheritDoc traversal (to inherit type hints)
● Make it faster
Ideas/plans
¯_(ツ)_/¯
github.com/ /BetterReflection
Better Reflection
Any questions? :)
https://joind.in/talk/9a5d8
James Titcumb @asgrim

More Related Content

PDF
On Functional Programming - A Clojurian Perspective
PDF
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
PPTX
Ricky Bobby's World
PPTX
Fact, Fiction, and FP
PPTX
PDF
Fertile Ground: The Roots of Clojure
ODP
EcmaScript 6
PPTX
Introduzione a C#
On Functional Programming - A Clojurian Perspective
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Ricky Bobby's World
Fact, Fiction, and FP
Fertile Ground: The Roots of Clojure
EcmaScript 6
Introduzione a C#

What's hot (20)

PDF
Swiftの関数型っぽい部分
PPTX
ES6 in Real Life
PDF
The Macronomicon
PPT
JDBC Core Concept
PPTX
Android Guava
PDF
Java Cheat Sheet
PDF
JavaScript ES6
PPS
Ecma script 5
PDF
Elm: give it a try
PDF
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
PDF
Javascript & Ajax Basics
PDF
Cycle.js: Functional and Reactive
PDF
Metaprogramming
PPTX
PHP Traits
PDF
The Ring programming language version 1.7 book - Part 35 of 196
PDF
Writing Clean Code in Swift
PPTX
MiamiJS - The Future of JavaScript
PDF
PHP Language Trivia
PPTX
Super Advanced Python –act1
PPTX
Perl6 a whistle stop tour
Swiftの関数型っぽい部分
ES6 in Real Life
The Macronomicon
JDBC Core Concept
Android Guava
Java Cheat Sheet
JavaScript ES6
Ecma script 5
Elm: give it a try
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Javascript & Ajax Basics
Cycle.js: Functional and Reactive
Metaprogramming
PHP Traits
The Ring programming language version 1.7 book - Part 35 of 196
Writing Clean Code in Swift
MiamiJS - The Future of JavaScript
PHP Language Trivia
Super Advanced Python –act1
Perl6 a whistle stop tour
Ad

Viewers also liked (20)

PDF
Foreign Direct Investments FDI in Serbia
PDF
Informatica solidale - cooperazione internazionale 9 aprile 2015
PPT
Stefan baltov-2014eng-1
PDF
Low power vlsi design workshop 1
PPTX
4 ginna laport
PPTX
New_Jenis_Kepribadian_Rusli_44310001
PPT
Ars breast cancer
PPT
Marlynne Grant researchED conf. 6th Sept 2014 - 30 minutes
PPSX
δοκιμή
PPTX
Risk Stratification for High Risk AML
PPTX
Futbol
PPT
Ivan chakarov-2013
PPT
Logo bruna
PPTX
Financing energy projects in Serbia
DOC
PDF
Ap 1 ubd 3rd quarter
PDF
Errors, Exceptions & Logging (PHPNW13 Uncon)
PPT
0830 q&a
PPT
Caderno pnaic ano2 texto sobre rotina
Foreign Direct Investments FDI in Serbia
Informatica solidale - cooperazione internazionale 9 aprile 2015
Stefan baltov-2014eng-1
Low power vlsi design workshop 1
4 ginna laport
New_Jenis_Kepribadian_Rusli_44310001
Ars breast cancer
Marlynne Grant researchED conf. 6th Sept 2014 - 30 minutes
δοκιμή
Risk Stratification for High Risk AML
Futbol
Ivan chakarov-2013
Logo bruna
Financing energy projects in Serbia
Ap 1 ubd 3rd quarter
Errors, Exceptions & Logging (PHPNW13 Uncon)
0830 q&a
Caderno pnaic ano2 texto sobre rotina
Ad

Similar to AST + Better Reflection (PHP Benelux 2016 Unconference) (7)

PDF
Mirror, mirror on the wall (PHPem Unconf 2015)
PDF
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
PDF
Mirror, mirror on the wall (Nomad PHP US 2015)
PDF
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
PPTX
Php meetup 20130912 reflection
PPT
Reflection-In-PHP
PDF
PHP Static Code Review
Mirror, mirror on the wall (PHPem Unconf 2015)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall (Nomad PHP US 2015)
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Php meetup 20130912 reflection
Reflection-In-PHP
PHP Static Code Review

More from James Titcumb (20)

PDF
Living the Best Life on a Legacy Project (phpday 2022).pdf
PDF
Tips for Tackling a Legacy Codebase (ScotlandPHP 2021)
PDF
Climbing the Abstract Syntax Tree (Midwest PHP 2020)
PDF
Best practices for crafting high quality PHP apps (Bulgaria 2019)
PDF
Climbing the Abstract Syntax Tree (php[world] 2019)
PDF
Best practices for crafting high quality PHP apps (php[world] 2019)
PDF
Crafting Quality PHP Applications (PHP Joburg Oct 2019)
PDF
Climbing the Abstract Syntax Tree (PHP Russia 2019)
PDF
Best practices for crafting high quality PHP apps - PHP UK 2019
PDF
Climbing the Abstract Syntax Tree (ScotlandPHP 2018)
PDF
Best practices for crafting high quality PHP apps (ScotlandPHP 2018)
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHP South Africa 2018)
PDF
Best practices for crafting high quality PHP apps (PHP South Africa 2018)
PDF
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)
PDF
Climbing the Abstract Syntax Tree (Southeast PHP 2018)
PDF
Crafting Quality PHP Applications (PHPkonf 2018)
PDF
Best practices for crafting high quality PHP apps (PHP Yorkshire 2018)
PDF
Crafting Quality PHP Applications: an overview (PHPSW March 2018)
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHP MiNDS March 2018)
PDF
Climbing the Abstract Syntax Tree (PHP UK 2018)
Living the Best Life on a Legacy Project (phpday 2022).pdf
Tips for Tackling a Legacy Codebase (ScotlandPHP 2021)
Climbing the Abstract Syntax Tree (Midwest PHP 2020)
Best practices for crafting high quality PHP apps (Bulgaria 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)
Best practices for crafting high quality PHP apps (php[world] 2019)
Crafting Quality PHP Applications (PHP Joburg Oct 2019)
Climbing the Abstract Syntax Tree (PHP Russia 2019)
Best practices for crafting high quality PHP apps - PHP UK 2019
Climbing the Abstract Syntax Tree (ScotlandPHP 2018)
Best practices for crafting high quality PHP apps (ScotlandPHP 2018)
Kicking off with Zend Expressive and Doctrine ORM (PHP South Africa 2018)
Best practices for crafting high quality PHP apps (PHP South Africa 2018)
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)
Climbing the Abstract Syntax Tree (Southeast PHP 2018)
Crafting Quality PHP Applications (PHPkonf 2018)
Best practices for crafting high quality PHP apps (PHP Yorkshire 2018)
Crafting Quality PHP Applications: an overview (PHPSW March 2018)
Kicking off with Zend Expressive and Doctrine ORM (PHP MiNDS March 2018)
Climbing the Abstract Syntax Tree (PHP UK 2018)

Recently uploaded (20)

PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Modernizing your data center with Dell and AMD
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Empathic Computing: Creating Shared Understanding
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
A Presentation on Artificial Intelligence
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Cloud computing and distributed systems.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
KodekX | Application Modernization Development
PDF
Electronic commerce courselecture one. Pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
NewMind AI Monthly Chronicles - July 2025
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Modernizing your data center with Dell and AMD
Understanding_Digital_Forensics_Presentation.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Empathic Computing: Creating Shared Understanding
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
A Presentation on Artificial Intelligence
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
“AI and Expert System Decision Support & Business Intelligence Systems”
Cloud computing and distributed systems.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Review of recent advances in non-invasive hemoglobin estimation
KodekX | Application Modernization Development
Electronic commerce courselecture one. Pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

AST + Better Reflection (PHP Benelux 2016 Unconference)