SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
PHP 7 EVOLUTION
taken from https://wiki.php.net/phpng
Performance
taken from https://wiki.php.net/phpng
Performance
http://zsuraski.blogspot.com/2014/07/benchmarking-phpng.html
Performance
Removed deprecated functionality
Scalar types declaration
<?php
// Coercive mode
function sumOfInts(int ...$ints)
{ 
    return array_sum($ints); 
} 
var_dump(sumOfInts(2, '3', 4.1)); 
//int(9)
Return type declarations
<?php
function arraysSum(array ...$arrays): array
{ 
    return array_map(function(array $array): int { 
        return array_sum($array); 
    }, $arrays); 
} 
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9])); 
/*
Array
(
[0] => 6
[1] => 15
[2] => 24
)
*/
Strict mode isn't strict enough
http://tryshchenko.com/archives/47
Unlike parameter type declarations, the type
checking mode used for return types depends
on the file where the function is defined, not
where the function is called. This is because
returning the wrong type is a problem with the
callee, while passing the wrong type is a
problem with the caller.
Null coalesce operator
<?php
// Fetches the value of $_GET['user'] and returns 'nobody' 
// if it does not exist. 
$username = $_GET['user'] ?? 'nobody'; 
// This is equivalent to: 
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; 
// Coalesces can be chained: this will return the first 
// defined value out of $_GET['user'], $_POST['user'], and 
// 'nobody'. 
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody'; 
Spaceship operator
<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
Constant arrays using define()
<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
Group use declarations
use somenamespace{ClassA, ClassB, ClassC as C}; 
use function somenamespace{fn_a, fn_b, fn_c}; 
use const somenamespace{ConstA, ConstB, ConstC};
Generator Return Expressions
$gen = (function() { 
    yield 1; 
    yield 2; 
    return 3; 
})();
foreach ($gen as $val) { 
    echo $val, PHP_EOL; 
} 
echo $gen->getReturn(), PHP_EOL; 
//1 
//2 
//3
Generator delegation
function gen()
{ 
    yield 1; 
    yield from gen2(); 
} 
function gen2()
{ 
    yield 2; 
    yield 3; 
} 
foreach (gen() as $val) 
{ 
    echo $val, PHP_EOL; 
} 
/*
1
2
3 */
Integer division with intdiv()
var_dump(intdiv(10, 3)); //3
PHP-NG
https://nikic.github.io/2015/05/05/Internal-value-representation-in-PHP-7-part-1.html
New zval structure
HashTable size reduced from 72 to 56 bytes
Switch from dlmalloc to something similar to jemalloc
Reduced MM overhead to 5%
x64 support
Exceptions handling
interface Throwable
|- Exception implements Throwable
|- ...
|- Error implements Throwable
|- TypeError extends Error
|- ParseError extends Error
|- ArithmeticError extends Error
|- DivisionByZeroError extends ArithmeticError
|- AssertionError extends Error
https://trowski.com/2015/06/24/throwable-exceptions-and-errors-in-php7/
Exceptions handling
interface Throwable
{ 
    public function getMessage(): string; 
    public function getCode(): int; 
    public function getFile(): string; 
    public function getLine(): int; 
    public function getTrace(): array; 
    public function getTraceAsString(): string; 
    public function getPrevious(): Throwable; 
    public function __toString(): string;
}
How to use it now
try { 
    // Code that may throw an Exception or Error. 
} catch (Throwable $t) { 
    // Executed only in PHP 7, will not match in PHP 5.x 
} catch (Exception $e) { 
    // Executed only in PHP 5.x, will not be reached in PHP 7 
}
Type errors
function add(int $left, int $right) 
{ 
    return $left + $right; 
} 
try { 
    $value = add('left', 'right'); 
} catch (TypeError $e) { 
    echo $e->getMessage(); 
} 
// Argument 1 passed to add() must be of the type integer, string given
ParseError
try { 
    require 'file-with-parse-error.php';
} catch (ParseError $e) { 
    echo $e->getMessage(), "n"; 
} 
//PHP Parse error: syntax error, unexpected ':', expecting ';' or '{'
ArithmeticError
try { 
    $value = 1 << ­1; 
} catch (ArithmeticError $e) { 
    echo $e->getMessage(), "n"; 
} 
DivisionByZeroError
try { 
    $value = 1 << ­1; 
} catch (DivisionByZeroError $e) { 
    echo $e->getMessage(), "n"; 
}
AssertionError
try { 
    $value = 1 % 0; 
} catch (DivisionByZeroError $e) { 
    echo $e->getMessage(), "n"; 
} 
//Fatal error: Uncaught AssertionError: assert($test === 0)
Applying function
//PHP5 WAY 
PHP 
<?php
class TestClass { 
  protected $b = 'hello world'; 
} 
//function ­ getter 
$getB = function() { 
  return $this->b; 
  //pay attention, context is undefined now! 
}; 
$applied = $getB->bindTo(new TestClass, 'TestClass'); 
echo $applied();
Applying function
//PHP7 WAY 
<?php
class TestClass { 
  protected $b = 'hello world'; 
} 
  
//function ­ getter 
  
$getB = function() { 
  return $this->b; 
  //pay attention, context is undefined now! 
}; 
  
  
echo $getB->call(new TestClass);
Continue coming soon
Tryshchenko Oleksandr
Dataart 2015
ensaierwa@gmail.com
skype:ensaier
 
Александр Трищенко: PHP 7 Evolution

Mais conteúdo relacionado

Mais procurados

Authentication Functions
Authentication FunctionsAuthentication Functions
Authentication Functions
Valerie Rickert
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
brian d foy
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
Leonardo Soto
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Anton Shemerey
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Masahiro Nagano
 

Mais procurados (20)

Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trial
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
Authentication Functions
Authentication FunctionsAuthentication Functions
Authentication Functions
 
The Truth About Lambdas in PHP
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHP
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
ZF3 introduction
ZF3 introductionZF3 introduction
ZF3 introduction
 
Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8
 
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
 
My Development Story
My Development StoryMy Development Story
My Development Story
 
Zend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency InjectionZend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency Injection
 
PL/SQL Blocks
PL/SQL BlocksPL/SQL Blocks
PL/SQL Blocks
 
Lazy Data Using Perl
Lazy Data Using PerlLazy Data Using Perl
Lazy Data Using Perl
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
 
Business Rules with Brick
Business Rules with BrickBusiness Rules with Brick
Business Rules with Brick
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
 

Semelhante a Александр Трищенко: PHP 7 Evolution

PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
Nick Belhomme
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
PrinceGuru MS
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 

Semelhante a Александр Трищенко: PHP 7 Evolution (20)

Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Message in a bottle
Message in a bottleMessage in a bottle
Message in a bottle
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016
 
PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return Types
 

Mais de Oleg Poludnenko

Илья Андриенко: Вёрстка в проекте глазами “неверстальщика”
Илья Андриенко: Вёрстка в проекте глазами  “неверстальщика”Илья Андриенко: Вёрстка в проекте глазами  “неверстальщика”
Илья Андриенко: Вёрстка в проекте глазами “неверстальщика”
Oleg Poludnenko
 

Mais de Oleg Poludnenko (12)

Дмитрий Красун: Сегодня вы уйдете с новым представлением о REST
Дмитрий Красун: Сегодня вы уйдете с новым представлением о RESTДмитрий Красун: Сегодня вы уйдете с новым представлением о REST
Дмитрий Красун: Сегодня вы уйдете с новым представлением о REST
 
Иван Стеценко: ЯП Zephir. Панацея или лечение?
Иван Стеценко: ЯП Zephir. Панацея или лечение?Иван Стеценко: ЯП Zephir. Панацея или лечение?
Иван Стеценко: ЯП Zephir. Панацея или лечение?
 
Александр Трищенко: Phalcon framework
Александр Трищенко: Phalcon frameworkАлександр Трищенко: Phalcon framework
Александр Трищенко: Phalcon framework
 
Алексей Иванкин: Highload + PHP
Алексей Иванкин: Highload + PHPАлексей Иванкин: Highload + PHP
Алексей Иванкин: Highload + PHP
 
Антон Довгоброд: Highload и очереди задач на примере PHP + Gearman + Yii2
Антон Довгоброд: Highload и очереди задач на примере PHP + Gearman + Yii2Антон Довгоброд: Highload и очереди задач на примере PHP + Gearman + Yii2
Антон Довгоброд: Highload и очереди задач на примере PHP + Gearman + Yii2
 
Алексей Рыстенко: Highload и микросервисы
Алексей Рыстенко: Highload и микросервисыАлексей Рыстенко: Highload и микросервисы
Алексей Рыстенко: Highload и микросервисы
 
Алексей Плеханов: Новинки Laravel 5
Алексей Плеханов: Новинки Laravel 5Алексей Плеханов: Новинки Laravel 5
Алексей Плеханов: Новинки Laravel 5
 
Макс Волошин: Php + shell = ♥
Макс Волошин: Php + shell = ♥Макс Волошин: Php + shell = ♥
Макс Волошин: Php + shell = ♥
 
Дмитрий Тарасов: Google App Engine & PHP SDK
Дмитрий Тарасов: Google App Engine & PHP SDKДмитрий Тарасов: Google App Engine & PHP SDK
Дмитрий Тарасов: Google App Engine & PHP SDK
 
Алексей Рыстенко: Continuous Integration
Алексей Рыстенко: Continuous IntegrationАлексей Рыстенко: Continuous Integration
Алексей Рыстенко: Continuous Integration
 
Илья Андриенко: Вёрстка в проекте глазами “неверстальщика”
Илья Андриенко: Вёрстка в проекте глазами  “неверстальщика”Илья Андриенко: Вёрстка в проекте глазами  “неверстальщика”
Илья Андриенко: Вёрстка в проекте глазами “неверстальщика”
 
Алексей Плеханов: 25 причин попробовать Laravel
Алексей Плеханов: 25 причин попробовать LaravelАлексей Плеханов: 25 причин попробовать Laravel
Алексей Плеханов: 25 причин попробовать Laravel
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
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
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Александр Трищенко: PHP 7 Evolution