SlideShare a Scribd company logo
1 of 35
Download to read offline
What is new in PHP 8
Haim Michael
March 24th
, 2021
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
life
michae
l
Let's be on The Edge
www.lifemichael.com
© 2008 Haim Michael 20150805
PHP 8
© 2008 Haim Michael 20150805
Union Types
 Union types is a collection of two or more types that either
one of them can be used.The void type can never be part of a
union type. The void type indicates that there isn't a returned
value.
<?php
class A
{
public function foo(X|C $input): Z|W|U
{
}
}
?>
© 2008 Haim Michael 20150805
JIT Compiler
 The virtual machine was improved. JIT (Just In Time)
capabilities were added.
 JIT virtual machines continuously analyze the code being
executed and identify parts worth additional compilation.
© 2008 Haim Michael 20150805
The Nullsafe Operator
 When having a variable that might hold the null value we
can avoid the if statement when using that variable for
calling a method and use the null safe operator instead.
$result = $ob ? $ob->getMagic() : 99;
© 2008 Haim Michael 20150805
The Nullsafe Operator
<?php
class Person {
private $magic;
function __construct($num) {
$this->magic = $num;
}
function getMagic() {
return $this->magic;
}
}
function findPerson() {
//...
return null;
}
$ob = findPerson();
$result = $ob ? $ob->getMagic() : 99;
echo $result;
?>
© 2008 Haim Michael 20150805
Arguments Naming
 When calling a function we can specify for each and every
argument we pass the name of the parameter it targets.
© 2008 Haim Michael 20150805
Arguments Naming
<?php
class Utils
{
public static function total(int $num1, int $num2):int
{
$result = $num1 + $num2;
return $result;
}
}
$a = 3;
$b = 6;
$sum = Utils::total(num1:$a,num2:$b);
echo $sum;
?>
© 2008 Haim Michael 20150805
Attributes
 We can now use attributes (AKA decorators and annotations
in other programming languages) and develop new ones.
<?php
#[OurAttribute]
class Foo
{
#[OurAttribute]
public const FOO = 'foo';
#[OurAttribute]
public $x;
#[OurAttribute]
public function f(#[OurAttribute] $bar) { }
}
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD |
Attribute::TARGET_PARAMETER | Attribute::TARGET_PROPERTY)]
class OurAttribute
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
}
?>
© 2008 Haim Michael 20150805
Attributes
 We can now use attributes (AKA decorators and annotations
in other programming languages) and develop new ones.
<?php
#[OurAttribute]
class Foo
{
#[OurAttribute]
public const FOO = 'foo';
#[OurAttribute]
public $x;
#[OurAttribute]
public function f(#[OurAttribute] $bar) { }
}
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD |
Attribute::TARGET_PARAMETER | Attribute::TARGET_PROPERTY)]
class OurAttribute
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
}
?>
© 2008 Haim Michael 20150805
Match Expression
 We can now use match expressions instead of the well known
switch statements.
<?php
function f($num) {
$result = match($num) {
0 => "Zero",
1 => "One",
'1', '2', '3' => "Number",
default => "Unknown"
};
return $result;
}
$temp = f(77);
echo $temp;
?>
© 2008 Haim Michael 20150805
Constructor Properties Promotion
 We can now define a constructor and add access modifiers to
its parameters. Doing so will promote the paremeters into
properties.
© 2008 Haim Michael 20150805
Constructor Properties Promotion
<?php
class Rectangle {
function __construct(
private int $width,
private int $height) {}
function area() {
return $this->width * $this->height;
}
}
$ob = new Rectangle(3,4);
echo $ob->area();
?>
© 2008 Haim Michael 20150805
The static Return Type
 We can now define a method that its return type is static.
 When calling such method it is possible to use its returned
value for calling static methods.
© 2008 Haim Michael 20150805
The static Return Type
<?php
class Foo
{
public function a(): static
{
echo "a";
return new static();
}
public static function b(): static
{
echo "b";
return new static();
}
}
(new Foo())->a()::b();
?>
© 2008 Haim Michael 20150805
The mixed Type
 We can define a function specifying that its returned value is
of the type mixed. Doing so, it would be possible to return
any of the following types: array, bool, callable, int, float, null,
object, resource and string.
function f(): ?mixed {}
© 2008 Haim Michael 20150805
The Throw Expression
 The throw statement has become an expression. It is now
possible to throw exceptions in many new places.
© 2008 Haim Michael 20150805
Private Methods Inheritance
 When extending another class, that already includes a
specific private methods, we can now declare that method
with a different signature.
© 2008 Haim Michael 20150805
Private Methods Inheritance
<?php
class A {
private function f($num1) {
return 10*$num1;
}
}
class B extends A {
private function f() {
echo "Bex";
}
function g() {
$this->f();
}
}
(new B())->g();
?>
© 2008 Haim Michael 20150805
The WeakMap Class
 We can now enjoy the WeakMap class when handling heavy
objects that relatively consume more resources.
 The WeakMap class was built upon the WeakRefs RFC. The
WeakMap object holds references to objects, that don't
prevent them from being garbage collected.
© 2008 Haim Michael 20150805
The WeakMap Class
<?php
class VideoClip {
function __construct(private string $title) {}
function __toString() {
return "book... ".$this->title;
}
}
class ID {
function __construct(private int $id) {}
}
$wm = new WeakMap();
$k = new ID(123);
$wm[$k] = new VideoClip("Matrix 1");
echo $wm[$k];
?>
© 2008 Haim Michael 20150805
The ::class Class
 We can now use the ::class feature on objects (so far it was
possible on classes only).
© 2008 Haim Michael 20150805
The ::class Class
<?php
class VideoClip {
function __construct(private string $title) {}
function __toString() {
return "book... ".$this->title;
}
}
$v = new VideoClip("Matrix 1");
echo VideoClip::class;
echo $v::class;
?>
© 2008 Haim Michael 20150805
Catchless Catches
 We can now omit the variable when catching an exception
using the catch block.
<?php
try {
//...
} catch (MyException) {
//...
}
?>
© 2008 Haim Michael 20150805
The Stringable Interface
 Using this new type we can type hint anything that
implements the __toString() method.
© 2008 Haim Michael 20150805
The str_contains Function
 Using this function we can check whether a specific string
contains another specific string. This new function allows us
to avoid the strpos() function when checking whether one
string contains another one.
© 2008 Haim Michael 20150805
The str_contains Function
<?php
$a = "love";
$b = "we love php";
if (str_contains($b,$a)) {
echo "love";
}
?>
© 2008 Haim Michael 20150805
Traits with Abstract Methods
 Till PHP 8 it was possible to define a trait that includes an
abstract method but the compiler didn't check whether that
class that uses the trait does indeed implement the abstract
method.
 As of PHP 8, the compiler does verify that the class
implements the abstract methods coming from the trait.
© 2008 Haim Michael 20150805
Traits with Abstract Methods
<?php
trait Flyable {
abstract public function fly(int $input): void;
}
class UsesTrait
{
use Flyable;
public function fly($input)
{
//..
}
}
?>
© 2008 Haim Michael 20150805
The ext-json Extension Availability
 As of PHP 8, the ext-json extension is always available. There
is no need to check whether it was already installed... or not.
© 2008 Haim Michael 20150805
Consistent Type Errors
 As of PHP 8, internal functions will throw error (instead of
warning messages or returning null), the same as user
defined functions behave.
© 2008 Haim Michael 20150805
Engine (Warnings) Errors
 As of PHP 8, many of the PHP engine warnings have become
errors.
© 2008 Haim Michael 20150805
The @ Operator
 As of PHP 8, the @ operator no longer silences fatal errors.
This small change might reveal errors that were hidden so far.
© 2008 Haim Michael 20150805
Concatenation Precedence
 As of PHP 8, when printing to the screen an expression that
includes the use of the mathematical operator +, the
mathematical operator + will take precedence over the string
concatenation . operator.
<?php
$a = 3;
$b = 4;
echo "sum is ".$a+$b;
?>
© 2009 Haim Michael All Rights Reserved 35
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
+972+54+6655837 (whatsapp)
life
michael

More Related Content

What's hot

08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
farhan amjad
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Mayank Jalotra
 

What's hot (17)

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
03. oop concepts
03. oop concepts03. oop concepts
03. oop concepts
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
05. inheritance
05. inheritance05. inheritance
05. inheritance
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
 

Similar to What is new in PHP

Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2
Wildan Maulana
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
Maurizio Pelizzone
 

Similar to What is new in PHP (20)

PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
 
PHP Versions Upgradation - What's New vs Old Version.pdf
PHP Versions Upgradation - What's New vs Old Version.pdfPHP Versions Upgradation - What's New vs Old Version.pdf
PHP Versions Upgradation - What's New vs Old Version.pdf
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Embrace dynamic PHP
Embrace dynamic PHPEmbrace dynamic PHP
Embrace dynamic PHP
 
Hack programming language
Hack programming languageHack programming language
Hack programming language
 
Hack Programming Language
Hack Programming LanguageHack Programming Language
Hack Programming Language
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
 
PHP 5.4 New Features
PHP 5.4 New FeaturesPHP 5.4 New Features
PHP 5.4 New Features
 
Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
 
Dependency Injection Smells
Dependency Injection SmellsDependency Injection Smells
Dependency Injection Smells
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 

More from Haim Michael

More from Haim Michael (20)

Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]
 
Python Jump Start
Python Jump StartPython Jump Start
Python Jump Start
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

What is new in PHP

  • 1. What is new in PHP 8 Haim Michael March 24th , 2021 All logos, trade marks and brand names used in this presentation belong to the respective owners. life michae l Let's be on The Edge www.lifemichael.com
  • 2. © 2008 Haim Michael 20150805 PHP 8
  • 3. © 2008 Haim Michael 20150805 Union Types  Union types is a collection of two or more types that either one of them can be used.The void type can never be part of a union type. The void type indicates that there isn't a returned value. <?php class A { public function foo(X|C $input): Z|W|U { } } ?>
  • 4. © 2008 Haim Michael 20150805 JIT Compiler  The virtual machine was improved. JIT (Just In Time) capabilities were added.  JIT virtual machines continuously analyze the code being executed and identify parts worth additional compilation.
  • 5. © 2008 Haim Michael 20150805 The Nullsafe Operator  When having a variable that might hold the null value we can avoid the if statement when using that variable for calling a method and use the null safe operator instead. $result = $ob ? $ob->getMagic() : 99;
  • 6. © 2008 Haim Michael 20150805 The Nullsafe Operator <?php class Person { private $magic; function __construct($num) { $this->magic = $num; } function getMagic() { return $this->magic; } } function findPerson() { //... return null; } $ob = findPerson(); $result = $ob ? $ob->getMagic() : 99; echo $result; ?>
  • 7. © 2008 Haim Michael 20150805 Arguments Naming  When calling a function we can specify for each and every argument we pass the name of the parameter it targets.
  • 8. © 2008 Haim Michael 20150805 Arguments Naming <?php class Utils { public static function total(int $num1, int $num2):int { $result = $num1 + $num2; return $result; } } $a = 3; $b = 6; $sum = Utils::total(num1:$a,num2:$b); echo $sum; ?>
  • 9. © 2008 Haim Michael 20150805 Attributes  We can now use attributes (AKA decorators and annotations in other programming languages) and develop new ones. <?php #[OurAttribute] class Foo { #[OurAttribute] public const FOO = 'foo'; #[OurAttribute] public $x; #[OurAttribute] public function f(#[OurAttribute] $bar) { } } #[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD | Attribute::TARGET_PARAMETER | Attribute::TARGET_PROPERTY)] class OurAttribute { public $value; public function __construct($value) { $this->value = $value; } } ?>
  • 10. © 2008 Haim Michael 20150805 Attributes  We can now use attributes (AKA decorators and annotations in other programming languages) and develop new ones. <?php #[OurAttribute] class Foo { #[OurAttribute] public const FOO = 'foo'; #[OurAttribute] public $x; #[OurAttribute] public function f(#[OurAttribute] $bar) { } } #[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD | Attribute::TARGET_PARAMETER | Attribute::TARGET_PROPERTY)] class OurAttribute { public $value; public function __construct($value) { $this->value = $value; } } ?>
  • 11. © 2008 Haim Michael 20150805 Match Expression  We can now use match expressions instead of the well known switch statements. <?php function f($num) { $result = match($num) { 0 => "Zero", 1 => "One", '1', '2', '3' => "Number", default => "Unknown" }; return $result; } $temp = f(77); echo $temp; ?>
  • 12. © 2008 Haim Michael 20150805 Constructor Properties Promotion  We can now define a constructor and add access modifiers to its parameters. Doing so will promote the paremeters into properties.
  • 13. © 2008 Haim Michael 20150805 Constructor Properties Promotion <?php class Rectangle { function __construct( private int $width, private int $height) {} function area() { return $this->width * $this->height; } } $ob = new Rectangle(3,4); echo $ob->area(); ?>
  • 14. © 2008 Haim Michael 20150805 The static Return Type  We can now define a method that its return type is static.  When calling such method it is possible to use its returned value for calling static methods.
  • 15. © 2008 Haim Michael 20150805 The static Return Type <?php class Foo { public function a(): static { echo "a"; return new static(); } public static function b(): static { echo "b"; return new static(); } } (new Foo())->a()::b(); ?>
  • 16. © 2008 Haim Michael 20150805 The mixed Type  We can define a function specifying that its returned value is of the type mixed. Doing so, it would be possible to return any of the following types: array, bool, callable, int, float, null, object, resource and string. function f(): ?mixed {}
  • 17. © 2008 Haim Michael 20150805 The Throw Expression  The throw statement has become an expression. It is now possible to throw exceptions in many new places.
  • 18. © 2008 Haim Michael 20150805 Private Methods Inheritance  When extending another class, that already includes a specific private methods, we can now declare that method with a different signature.
  • 19. © 2008 Haim Michael 20150805 Private Methods Inheritance <?php class A { private function f($num1) { return 10*$num1; } } class B extends A { private function f() { echo "Bex"; } function g() { $this->f(); } } (new B())->g(); ?>
  • 20. © 2008 Haim Michael 20150805 The WeakMap Class  We can now enjoy the WeakMap class when handling heavy objects that relatively consume more resources.  The WeakMap class was built upon the WeakRefs RFC. The WeakMap object holds references to objects, that don't prevent them from being garbage collected.
  • 21. © 2008 Haim Michael 20150805 The WeakMap Class <?php class VideoClip { function __construct(private string $title) {} function __toString() { return "book... ".$this->title; } } class ID { function __construct(private int $id) {} } $wm = new WeakMap(); $k = new ID(123); $wm[$k] = new VideoClip("Matrix 1"); echo $wm[$k]; ?>
  • 22. © 2008 Haim Michael 20150805 The ::class Class  We can now use the ::class feature on objects (so far it was possible on classes only).
  • 23. © 2008 Haim Michael 20150805 The ::class Class <?php class VideoClip { function __construct(private string $title) {} function __toString() { return "book... ".$this->title; } } $v = new VideoClip("Matrix 1"); echo VideoClip::class; echo $v::class; ?>
  • 24. © 2008 Haim Michael 20150805 Catchless Catches  We can now omit the variable when catching an exception using the catch block. <?php try { //... } catch (MyException) { //... } ?>
  • 25. © 2008 Haim Michael 20150805 The Stringable Interface  Using this new type we can type hint anything that implements the __toString() method.
  • 26. © 2008 Haim Michael 20150805 The str_contains Function  Using this function we can check whether a specific string contains another specific string. This new function allows us to avoid the strpos() function when checking whether one string contains another one.
  • 27. © 2008 Haim Michael 20150805 The str_contains Function <?php $a = "love"; $b = "we love php"; if (str_contains($b,$a)) { echo "love"; } ?>
  • 28. © 2008 Haim Michael 20150805 Traits with Abstract Methods  Till PHP 8 it was possible to define a trait that includes an abstract method but the compiler didn't check whether that class that uses the trait does indeed implement the abstract method.  As of PHP 8, the compiler does verify that the class implements the abstract methods coming from the trait.
  • 29. © 2008 Haim Michael 20150805 Traits with Abstract Methods <?php trait Flyable { abstract public function fly(int $input): void; } class UsesTrait { use Flyable; public function fly($input) { //.. } } ?>
  • 30. © 2008 Haim Michael 20150805 The ext-json Extension Availability  As of PHP 8, the ext-json extension is always available. There is no need to check whether it was already installed... or not.
  • 31. © 2008 Haim Michael 20150805 Consistent Type Errors  As of PHP 8, internal functions will throw error (instead of warning messages or returning null), the same as user defined functions behave.
  • 32. © 2008 Haim Michael 20150805 Engine (Warnings) Errors  As of PHP 8, many of the PHP engine warnings have become errors.
  • 33. © 2008 Haim Michael 20150805 The @ Operator  As of PHP 8, the @ operator no longer silences fatal errors. This small change might reveal errors that were hidden so far.
  • 34. © 2008 Haim Michael 20150805 Concatenation Precedence  As of PHP 8, when printing to the screen an expression that includes the use of the mathematical operator +, the mathematical operator + will take precedence over the string concatenation . operator. <?php $a = 3; $b = 4; echo "sum is ".$a+$b; ?>
  • 35. © 2009 Haim Michael All Rights Reserved 35 Questions & Answers Thanks for Your Time! Haim Michael haim.michael@lifemichael.com +972+3+3726013 ext:700 +972+54+6655837 (whatsapp) life michael