SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
5.
Agenda
• Mudanças para o usuário
• Mudanças internas
• PHP.NEXT
6.
Mudanças para o usuário
• Quebras de compatibilidade
• Novos operadores
• Erros e exceções
• Indução de tipo escalar (Scalar type hint)
• Declaração de tipo de retorno (Return type hint)
• Classes anônimas (Anonymous classes)
• Palavras-chave semi-reservadas
8.
Quebras de compatibilidade
• Construtores do PHP 4
1 class Post {
2 public function post() {
3 echo 'post';
4 }
5 }
$post = new Post();
$post = new DomainPost();
1 namespace Domain {
2 class Post {
3 public function post() {
4 echo 'post';
5 }
6 }
7 }
9.
Quebras de compatibilidade
• Mudanças de sintaxe (Uniform variable syntax)
• Novas combinações de operadores
$foo()['bar']()
[$obj1, $obj2][0]->prop
$foo->bar()::baz()
$foo->bar()()
(function () {})()
10.
Quebras de compatibilidade
• Mudanças de sintaxe (Uniform variable syntax)
• Acesso indireto à variáveis, propriedades e métodos
Expressão Interpretação no PHP 5 Interpretação no PHP 7
$$foo['bar']['baz'] ${$foo['bar']['baz']} ($$foo)['bar']['baz']
$foo->$bar['baz'] $foo->{$bar['baz']} ($foo->$bar)['baz']
$foo->$bar['baz']() $foo->{$bar['baz']}() ($foo->$bar)['baz']()
Foo::$bar['baz']() Foo::{$bar['baz']}() (Foo::$bar)['baz']()
15.
Novos operadores
• Group use
use EblockDomainDirectoryEntity{
Consigner,
Location as ConsignerLocation,
User
};
use EblockDomainDirectory{
DTO{
ConsignerUpdate as UpdateConsigner
},
Entity{
Consigner,
Location,
User
}
};
17.
Erros e exceções
• Usuário pode capturar qualquer chamada que possa gerar erros fatais
• A maioria dos error E_RECOVERABLE viraram Exceptions
• Erros E_STRICT foram re-classificados como E_WARN e E_NOTICE
• Erros fatais são ou herdam a classe "Error"
• Erros de análise sintática geram "ParseError"
• Ambos "Error" e "Exception" implementam a interface "Throwable"
19.
Erros e exceções
1 echo 'PHP ' . phpversion() . PHP_EOL;
2
3 try {
4 $foo = new foo();
5 } catch (Exception $e) {
6 echo 'I am an exception: ' . $e->getMessage() . PHP_EOL;
7 } catch (Error $e) {
8 echo 'I am an error: ' . $e->getMessage() . PHP_EOL;
9 } catch (Throwable $t) {
10 echo 'I am throwable: ' . $t->getMessage() . PHP_EOL;
11 }
12
13 // PHP 5.6.19
14 // Fatal error: Class 'foo' not found in
15 // Documents/PHP7/throwable.php on line 5
16
17 // PHP 7.0.4
18 // I am an error: Class 'foo' not found
20.
Indução de tipo escalar
• Funciona de duas formas distintas:
• Weak mode (Coercivo)
• Strict (Forte)
declare(strict_types=1);
21.
Indução de tipo escalar
Tipo declarado int float string bool object
int yes yes* yes† yes no
float yes yes yes† yes no
string yes yes yes yes yes‡
bool yes yes yes yes no
* Somente pontos flutuantes não-NaN e entre PHP_INT_MIN e PHP_INT_MAX serão aceitos.
† Se for uma string numérica
‡ Somente se o objeto tiver o método __toString()
function setEnabled(bool $enabled) { /* ... */ }
22.
Indução de tipo escalar
1 declare(strict_types=1);
2
3 function welcome(string $name) {
4 echo 'Welcome to the show, ' . $name;
5 }
6
7 welcome('Guilherme');
8 // Welcome to the show, Guilherme
9
10 welcome(42);
11 // TypeError: Argument 1 passed to welcome()
12 // must be of the type string, integer given
23.
Declaração de tipo de retorno
function getCreator(): UserInterface {
return $this->getPost()->getAuthor();
}
function getAuthor(): UserInterface {
return 'Guilherme Blanco';
}
getAuthor();
// TypeError: Return value of getAuthor() must be
// an instance of UserInterface, string returned
24.
Classes anônimas
// Pre PHP 7
class EchoLogger implements LoggerInterface {
public function log($message) {
echo $message;
}
}
$application->setLogger(new Logger());
// PHP 7, seu lindo! <3
$application->setLogger(new class () implements LoggerInterface {
public function log(string $message) {
echo $message;
}
});
25.
Palavras-chave semi-reservadas
• abstract
• and
• array
• as
• break
• callable
• case
• catch
• class*
• clone
• const
• continue
• declare
• default
• die
• do
• global
• goto
• if
• implements
• include
• include_once
• instanceof
• insteadof
• interface
• list
• namespace
• new
• or
• parent
• print
• private
• protected
• public
• require
• require_once
• return
• self
• static
• switch
• throw
• trait
• try
• use
• var
• while
• xor
• yield
• echo
• else
• elseif
• enddeclare
• endfor
• endforeach
• endif
• endswitch
• endwhile
• exit
• extends
• final
• finally
• for
• foreach
• function
28.
Mudanças internas
• Árvore de sintaxe abstrata (Abstract Syntax Tree)
• Suporte completo a 64 bits
• Large File Support (LFS)
• Strings maiores que 231
• Suporte a inteiros de 64 bits
• Novo gerenciamento de memória
• ZVALs são alocados na stack
• refcount mais preciso
• Nova implementação de segurança sobre threads
• Thread safety no PHP 5 implicava numa penalização de performance em ~20%
• Otimização de estruturas de dados
31.
Otimização de estruturas de dados
• ~20% do tempo gasto no PHP 5 era referente à alocação de memória
• No PHP 7, foi reduzido o número de alocações
• No PHP 7, foi reduzido o consumo de memória
• No PHP 7, foi reduzido o número de indicações
• O motor de execução agora utiliza stack push e gerencia argumentos
• Chamada pra funções foram drasticamente refatoradas
• Variáveis no PHP 7 são cacheadas de forma mais eficiente
• String são refcounted
32.
Otimização de estruturas de dados
• ZVAL no PHP 5
1 typedef union _zvalue_value {
2 long lval;
3 double dval;
4 struct {
5 char *val;
6 int len;
7 } str;
8 HashTable *ht;
9 zend_object_value obj;
10 zend_ast *ast;
11 } zvalue_value;
1 struct _zval_struct {
2 zvalue_value value;
4 zend_uint refcount__gc;
5 zend_uchar type;
6 zend_uchar is_ref__gc;
7 } zval;
33.
ZVAL no PHP 5
value
ZVAL
ty
Crédito: Nikita Popov
34.
ZVAL no PHP 5
value (simple):
null, bool, int, float
ZVAL
ty
Crédito: Nikita Popov
35.
ZVAL no PHP 5
value (complex):
ZVAL
ty
complex data structure:
string, array, object
Crédito: Nikita Popov
36.
ZVAL no PHP 5
1 $a = [];
zval *$a value (complex):
ZVAL
ty
complex data structure:
string, array, object
refcount = 1
Crédito: Nikita Popov
37.
ZVAL no PHP 5
zval *$a
1 $a = [];
2 $b = $a;
value (complex):
ZVAL
ty
complex data structure:
string, array, object
refcount = 1
Crédito: Nikita Popov
38.
ZVAL no PHP 5
zval *$a
1 $a = [];
2 $b = $a;
value (complex):
ZVAL
ty
complex data structure:
string, array, object
refcount = 2
zval *$b
Crédito: Nikita Popov
42.
ZVAL no PHP 7
$a
1 $a = [];
2 $b = $a;
$b
complex data structure:
string, array, object
refcount = 2
value (complex):
type_info
value (complex):
type_info
Crédito: Nikita Popov
43.
PHP 5 vs. PHP 7 ZVAL
zval *
value (simple):
null, bool, int, float
tyrefcount = 1
1 alocação de memória
1 nível de indireção
40 bytes
value (simple):
null, bool, int, float
type_info
sem alocações de memória
sem indireções
16 bytes
44.
PHP 5 vs. PHP 7 ZVAL
zval *
complex data structure:
string, array, object
value (complex):
tyrefcount = 1
2 alocações de memória
2 níveis de indireção
40 bytes
complex data structure:
string, array, object
refcount = 1
value (complex):
type_info
1 alocação de memória
1 nível de indireção
24 bytes
45.
PHP 5 vs. PHP 7 Objetos
zval
object store bucket
object real
tabela de propriedades
valor da propriedade
zval
objeto real
+
tabela de propriedades
(incluindo valores)
PHP 5 PHP 7
Alocações 2 + 1 / propriedade 1 + 0 / propriedade
Tamanho 96 + 40 / propriedade 48 + 16 / propriedade
Indireções 4 1