PHP Leeds, Wales, United Kingdom
Strong typing in PHP
adoption, evolution and organisation
AGENDA
• PHP Type hints system
• Adoption
• Evolution
• Organisation
SPEAKER
• Damien Seguy
• CTO @exakat
• Static analysis expert
• Retirement home for elePHPants
Everyone uses typehinting
97%
3%
With Typehints Without typehint
No
typeh
ints
Adoption Hard
part
A
d
or
at
or
s
Everyone uses typehinting
Adoption
Typehints as debug tactics
• Set up a typehint
• Wait for the 'Fatal error'
• Fix the calling code, now that you know where it is
• Remove it in production
• Leave it in development
<?php
foo("a");
foo(1);
foo(new x);
foo(array());
function foo(string $s) {
echo $s;
}
class x {
function __toString()
{ return "a"; }
}
?>
Your code is already typed
• Typehints are already used in the code
• PHP, and strict_types
• is_string(), is_array(), instanceof…
• Coding conventions
Coding conventions
• The type is in the name of the argument
• $string, $array
• $user = new User();
<?php
function shorten($string) {
return substr($string, 0, 5);
}
function getPattern(array $ints) { }
function (StringClass $string) { }
?>
Moving type checks to the signature
• is_a(), is_subclass_of(), instanceof, ===
null
• is_string(), is_array()
• (int), (string)…
<?php
function bar($user) {
if ($user === null) {
throw new TypeError();
}
if (!$user instanceof User)) {
throw new TypeError();
}
return $user->validate();
}
?>
Moving type checks to the signature
• is_a(), is_subclass_of(), instanceof, ===
null
• is_string(), is_array()
• (int), (string)…
<?php
function bar(Usager $user) {
return $user->validate();
}
?>
Moving type checks to the signature
• is_a(), is_subclass_of(), instanceof, ===
null
• is_string(), is_array()
• (int), (string)…
<?php
function bar($price) {
return floor((float) $price) * 1.21;
}
?>
Follow the lead
<?php
function bar($argument) {
return substr($argument, 0, 10);
}
?>
Follow the lead
<?php
function bar(string $argument) {
return substr($argument, 0, 10);
}
?>
Follow the lead
<?php
function bar($argument) : string {
return substr($argument, 0, 10);
}
?>
Follow the lead
<?php
function bar(string $argument) : string {
return substr($argument, 0, 10) ?: '';
}
?>
Substr() returns string OR false
Strong typing : adoption, adaptation and organisation
Backward with the return types
<?php
function bar($argument) {
return foo($argument);
}
function foo($x) {
return barbar($x);
}
function barbar($y) : string {
//...
}
?>
Forward with caution
<?php
function bar3($argument) {
return foo(null);
}
?>
<?php
function bar($argument) {
return foo($argument);
}
function foo($x) {
return barbar($x);
}
function barbar(string $y) {
//...
}
?>
<?php
function bar2($argument) {
return foo(22);
}
?>
Wait for PHP 8.0
<?php
function foo($x) {
if (rand(1, 3)) {
return 1;
} else {
return barbar($x);
}
}
function barbar($y) : string {
//...
}
?>
Adoption
• Use it for debugging purposes
• Follow the types that are already there
• PHP
• Your framework
• Propagate your own types
• Return types are easy, argument types need caution
Evolution
Evolution
• Typehints now have impact on your code
• Wait for PHP 8.0 union types
• Single type is a constraint and a tool
Impact of defaults
<?php
function foo($x = -1) {
if ($x === -1) {
return '';
} else {
return substr($x, 0, 1);
}
}
?>
Impact of defaults
<?php
class foo {
const DEFAULT = -1;
private $bar = self::DEFAULT;
public function foo() {
if ($this->bar === DEFAULT) {
return '';
} else {
return substr($this->bar, 0, 1);
}
}
?>
Ambiguous cases
<?php
function foo($b) {
return array_fill(0, 10, $b);
}
function bar($a) {
return shell_exec($a);
}
?>
Ambiguous cases
<?php
declare(strict_types = 1);
function foo(array $a) { }
foo(['a', 'b', 'c', 'd' ]);
foo(['a', 'b', 'c', null, 2]);
?>
• array()
• No generic in PHP
• Use attributes and
annotations
Dubious cases
<?php
declare(strict_types = 1);
class x {
function __set($name, $a) {
//...
}
}
$x = (new x);
$x->c = 3;
?>
Fossilisation stage
• Method signatures
• Arguments count
• Compulsory versus optional
• Type
• Default values
• Visibility
Fossilisation stage
• Modify M1() in C3
• Modify M1() in C1
• Modify M1() in C2 and C4
• Modify M1() in C5
• Modify M1() in C6
• …
Evolution
no
type
scalar types class
types
non-null
interfaces
Evolution
0%
18%
35%
53%
70%
88%
object iterable callable int bool void string array scalar Classes
Evolution
• Scalar types cannot evolve
• Classes can evolve
• Class types don't need to be complex
• A price is not an int/float
• A path may be a string while a string is not a path
Evolution
no
type
scalar types
class
types
non-null
interfaces
No types
Evolution
Also no types
Evolution
Evolution
• Type hints reduces the number of possible paths in
the code
• Scalar are versatile
• They have a lot of connectivity
• Upgrading scalar types to class types reduce
complexity even more
Scalar types to classes
Evolution
Organisation
Organisation
• Typehinting has impact on the signature of a method
• This impact spreads all over the application
• It introduces a hierarchy of the classes
Classes order
Organisation
• A method returns one type
• A method has dependencies on
its arguments's type
• That object must be created
first
• A method has dependencies on
its constructor too
Classes order
Organisation
• A method returns one type
• A method has dependencies on
its arguments's type
• That object must be created
first
• A method has dependencies on
its constructor too
Classes order
Organisation
• Mysql (C1)
• Host/Login/Pwd (C2)
• Prepare (M1)
• Query (C3)
Classes order
Organisation
• Mysql (C1)
• Host/Login/Pwd (C2)
• Prepare (M1)
• Query (C3)
Classes order
Organisation
• Topological sorting of the classes
• One class has priority over another class when it is used as typehint
• There is no garantee for a single top class :
• Probably several top classes
• With scalar as argument, because they are so easy to tweak
Classes order
Organisation
Classes order
Organisation
Subsidiary questions
Organisation
• Why are there multiple methods with the same typehints?
• Potential double work
• How testable are the classes?
• How many objects do you need to create an instance?
• Can a method reach a specific type of class?
• The needed types may not be available
Adding typehints to your code base
• Adoption
• Follow the current code
• Evolution
• Refactor the code, use classes as typehints
• Organisation
• Use typehints to reduce complexity and plan evolutions
Subsidiary questions
Static analysis helps you type
• Exakat
• Typehint suggestion report, type inconsistencies and typehint report
• Phpdoctor
• Reports missing types
• Psalm
• Infers typehints on the fly
Subsidiary questions
Static analysis helps you type
• Exakat
• Typehint suggestion report, type inconsistencies and typehint report
• Phpdoctor
• Reports missing types
• Psalm
• Infers typehints on the fly
https://www.exakat.io/ | @exakat
O, diolch yn
fawr iawn
Classes order
Organisation
• M1 needs a property
• M2 provides that property
• M2 > M1()
• True in PHP 7.4+
• x::$a must not be accessed before
initialization
• True in PHP 7.0
• Call to a member function bar() on
null

More Related Content

PDF
Strong typing @ php leeds
PPT
Functional OOP, Clojure style
PDF
What can scala puzzlers teach us
PPTX
C++ overview
PDF
Introduction to Python for Plone developers
PDF
Real-World Scala Design Patterns
PPT
Scala Talk at FOSDEM 2009
PPTX
Practical type mining in Scala
Strong typing @ php leeds
Functional OOP, Clojure style
What can scala puzzlers teach us
C++ overview
Introduction to Python for Plone developers
Real-World Scala Design Patterns
Scala Talk at FOSDEM 2009
Practical type mining in Scala

What's hot (19)

PDF
Functional Programming In Practice
PDF
Effective Scala (JavaDay Riga 2013)
PPTX
Introduction to Java Programming
PPT
Csharp_mahesh
PDF
Introduction to Functional Programming with Scala
PPTX
Let’s have some fun with Power Query M language
PPTX
The Evolution of Scala
PDF
Introduction to Type Script by Sam Goldman, SmartLogic
PDF
Ruby para-programadores-php
PDF
Ruby1_full
PPTX
Introduction to Scala
PPTX
Groovy Programming Language
PDF
Functional programming in kotlin with Arrow [Sunnytech 2018]
ODP
A Tour Of Scala
PDF
Scala reflection
PPT
String and string manipulation
PDF
Few simple-type-tricks in scala
PPT
Php basics
PDF
Type Profiler: Ambitious Type Inference for Ruby 3
Functional Programming In Practice
Effective Scala (JavaDay Riga 2013)
Introduction to Java Programming
Csharp_mahesh
Introduction to Functional Programming with Scala
Let’s have some fun with Power Query M language
The Evolution of Scala
Introduction to Type Script by Sam Goldman, SmartLogic
Ruby para-programadores-php
Ruby1_full
Introduction to Scala
Groovy Programming Language
Functional programming in kotlin with Arrow [Sunnytech 2018]
A Tour Of Scala
Scala reflection
String and string manipulation
Few simple-type-tricks in scala
Php basics
Type Profiler: Ambitious Type Inference for Ruby 3
Ad

Similar to Strong typing : adoption, adaptation and organisation (20)

PDF
Php Online Training
PDF
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
PDF
Scala in practice - 3 years later
PDF
A Type-level Ruby Interpreter for Testing and Understanding
PDF
Php Crash Course - Macq Electronique 2010
PDF
TAKING PHP SERIOUSLY - Keith Adams
PPTX
C Sharp Course 101.5
PPTX
Introduction To PHP000000000000000000000000000000.pptx
PDF
型ヒントについて考えよう!
PPTX
Learn c++ Programming Language
PDF
Hsc IT 5. Server-Side Scripting (PHP).pdf
KEY
Developer testing 101: Become a Testing Fanatic
PPTX
Typescript ppt
PPT
Python ppt
PPTX
Unit 4-6 sem 7 Web Technologies.pptx
PPTX
Core java complete ppt(note)
Php Online Training
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Scala in practice - 3 years later
A Type-level Ruby Interpreter for Testing and Understanding
Php Crash Course - Macq Electronique 2010
TAKING PHP SERIOUSLY - Keith Adams
C Sharp Course 101.5
Introduction To PHP000000000000000000000000000000.pptx
型ヒントについて考えよう!
Learn c++ Programming Language
Hsc IT 5. Server-Side Scripting (PHP).pdf
Developer testing 101: Become a Testing Fanatic
Typescript ppt
Python ppt
Unit 4-6 sem 7 Web Technologies.pptx
Core java complete ppt(note)
Ad

More from Damien Seguy (20)

PDF
Qui a laissé son mot de passe dans le code
PDF
Analyse statique et applications
PDF
Top 10 pieges php afup limoges
PDF
Top 10 php classic traps DPC 2020
PDF
Meilleur du typage fort (AFUP Day, 2020)
PDF
Top 10 php classic traps confoo
PDF
Tout pour se préparer à PHP 7.4
PDF
Top 10 php classic traps php serbia
PDF
Top 10 php classic traps
PDF
Top 10 chausse trappes
PDF
Code review workshop
PDF
Understanding static analysis php amsterdam 2018
PDF
Review unknown code with static analysis php ce 2018
PDF
Everything new with PHP 7.3
PDF
Php 7.3 et ses RFC (AFUP Toulouse)
PDF
Tout sur PHP 7.3 et ses RFC
PDF
Review unknown code with static analysis php ipc 2018
PDF
Code review for busy people
PDF
Static analysis saved my code tonight
PDF
Machine learning in php las vegas
Qui a laissé son mot de passe dans le code
Analyse statique et applications
Top 10 pieges php afup limoges
Top 10 php classic traps DPC 2020
Meilleur du typage fort (AFUP Day, 2020)
Top 10 php classic traps confoo
Tout pour se préparer à PHP 7.4
Top 10 php classic traps php serbia
Top 10 php classic traps
Top 10 chausse trappes
Code review workshop
Understanding static analysis php amsterdam 2018
Review unknown code with static analysis php ce 2018
Everything new with PHP 7.3
Php 7.3 et ses RFC (AFUP Toulouse)
Tout sur PHP 7.3 et ses RFC
Review unknown code with static analysis php ipc 2018
Code review for busy people
Static analysis saved my code tonight
Machine learning in php las vegas

Recently uploaded (20)

PDF
CloudStack 4.21: First Look Webinar slides
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PPTX
Configure Apache Mutual Authentication
PPTX
Build Your First AI Agent with UiPath.pptx
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PDF
Convolutional neural network based encoder-decoder for efficient real-time ob...
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPTX
Chapter 5: Probability Theory and Statistics
PDF
A proposed approach for plagiarism detection in Myanmar Unicode text
PDF
Getting started with AI Agents and Multi-Agent Systems
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PPTX
TEXTILE technology diploma scope and career opportunities
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PPT
What is a Computer? Input Devices /output devices
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Five Habits of High-Impact Board Members
PDF
Flame analysis and combustion estimation using large language and vision assi...
CloudStack 4.21: First Look Webinar slides
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
Configure Apache Mutual Authentication
Build Your First AI Agent with UiPath.pptx
Zenith AI: Advanced Artificial Intelligence
The influence of sentiment analysis in enhancing early warning system model f...
Enhancing plagiarism detection using data pre-processing and machine learning...
Convolutional neural network based encoder-decoder for efficient real-time ob...
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Chapter 5: Probability Theory and Statistics
A proposed approach for plagiarism detection in Myanmar Unicode text
Getting started with AI Agents and Multi-Agent Systems
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
TEXTILE technology diploma scope and career opportunities
Final SEM Unit 1 for mit wpu at pune .pptx
Improvisation in detection of pomegranate leaf disease using transfer learni...
What is a Computer? Input Devices /output devices
1 - Historical Antecedents, Social Consideration.pdf
Five Habits of High-Impact Board Members
Flame analysis and combustion estimation using large language and vision assi...

Strong typing : adoption, adaptation and organisation