On Github tdutrion / talk-2016-02-02-php7-modern-php-ecosystem-falkirk-lug
By Thomas Dutrion / @tdutrion - 02/02/2016
Aberdeen (1st Wednesday) Edinburgh (2nd Tuesday) Glasgow (3rd Tuesday) Dundee (4rd Thursday)
https://www.scotlandphp.co.uk<!--include /text/header.html--> <!--getenv HTTP_USER_AGENT--> <!--ifsubstr $exec_result Mozilla--> Hey, you are using Netscape!<p> <!--endif--> <!--sql database select * from table where user='$username'--> <!--ifless $numentries 1--> Sorry, that record does not exist<p> <!--endif exit--> Welcome <!--$user-->!<p> You have <!--$index:0--> credits left in your account.<p> <!--include /text/footer.html-->
Unfortunately similar to what most people learn in universities and schools...
<?php class Car implement Vehicle { private $colour; public function hasFourWheels() { return true; } } $car = new Car(); var_dump($car->hasFourWheels());
<?php function add($item1, $item2) { return $item1 + $item2; } var_dump(add(1, 1)); // int(2) var_dump(add(1, 'test')); // int(1) var_dump(add(1, array('test'))); // Fatal error: Uncaught Error: Unsupported operand types
<?php class Car {} function functionUsingCar(Car $car) {} $car1 = new Car(); functionUsingCar($car1); $car2 = new stdClass(); functionUsingCar($car2); // Catchable fatal error: Argument 1 passed to functionUsingCar() // must be an instance of Car, stdClass given
<?php try { throw new Exception('an error occurred'); } catch (Exception $e) { echo $e->getMessage(); // an error occurred } try { trigger_error('an error occurred'); } catch (Exception $e) { echo $e->getMessage(); } // Notice: an error occurred in /in/MoXC0 on line 10
PHP tries to convert the value to the expected type before validating the argument (default behaviour).
<?php // Coercive mode function sumOfInts(int ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, '3', 4.1)); // result = 9 (2 + 3 + 4, 4.1 being converted to int)
Has to be declared in each file.
Also impacts return types, PHP build-in functions and extensions.
<?php declare (strict_types=1) // Strict mode function sumOfInts(int ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, 3, 4)); //int(9) var_dump(sumOfInts(2, '3', 4.1)); // Fatal error: Uncaught TypeError: Argument 2 passed to sumOfInts() // must be of the type integer, string given // Next TypeError: Argument 3 passed to sumOfInts() must be of the // type integer, float given
<?php function add($a, $b) : float { return $a + $b; } var_dump(1, 2); // float(3)
<?php declare (strict_types=1); function add($a, $b) : float { return $a + $b; } var_dump(1, 2); // float(3) var_dump(1.1, 2); // Fatal error: Uncaught TypeError: Return value of add() must // be of the type integer, float returned
Problem: how can you be sure you can run PHP programs?
Solution: Facebook and some PHP core contributors wrote a language specification based on PHP 5.6.
Using the community effort to write the same piece multiple times.
Writing recommandations for interoperability.
Currently: