new in php 7

53
New in PHP 7

Upload: vic-metcalfe

Post on 07-Aug-2015

134 views

Category:

Technology


1 download

TRANSCRIPT

New in PHP 7

Conference Confirmed

http://truenorthphp.ca

November 5, 6, 7@TrueNorthPHP

Talk to Pete or Vic about sponsorship opportunities. Call

for speakers and tickets coming soon.

http://gtaphp.org/ks

O’Reilly has offered our group 50% off all e-Books, other items also discounted. Discount

code: PCBW

• Ask questions at any time

• Point out mistakes at any time

• Slides will be posted online so there is no need to photograph slides

Roadmap

• New Features

• Backwards Compatibility Breaks

• Bug Fixes

• Wrap-up

• “Get the most” tips as we go

6.0?5.7?

Used with permission from https://www.flickr.com/photos/jeepersmedia/8030074932/. "PHP 7" on hat is

a modification from the original image.

New Features

Faster than PHP 7

Based on phpng

Many additional optimizations

Still getting considerably faster

Should rival hack for performance

Return types

function foo(): array { return [];}

function foo(): DateTime { return null; // invalid}

Return types

Class constructors, destructors and clone methods may not declare return types.

No void return type

Scalar Type Declarations

int, float, string and bool

“an atomic quantity that can hold only one value at a time”

- Wikipedia

integer or boolean

declare(strict_types=1)

Scalar Type Declarations

function add(int $a, int $b) { return $a + $b;}

echo add(1, 2); // 3echo add(1.1, 2); // 3

Scalar Type Declarations

declare(strict_types=1);

function add(int $a, int $b) { return $a + $b;}

echo add(1, 2); // 3echo add(1.1, 2); // Error

1.0 would also throw an error,but coercing an int to a float is ok.

<=>

function order_func($a, $b) { return $a <=> $b;}

echo 1 <=> 1; // 0echo 1 <=> 2; // -1echo 2 <=> 1; // 1

Anonymous classesclass MyLogger { public function log($msg) { print_r($msg . "\n"); }}$pusher->setLogger( new MyLogger() );

$pusher->setLogger(new class { public function log($msg) { print_r($msg . "\n"); }});

Old:

New:

Generator Return Values

function foo() { yield 1; yield 2; return 42;} $bar = foo();foreach ($bar as $element) { echo $element, "\n";} var_dump($bar->getReturn());

12int(42)

Generator Delegationfunction myGeneratorFunction($foo) { // ... do some stuff with $foo ... $bar = yield from factoredComputation1($foo); // ... do some stuff with $bar ... $baz = yield from factoredComputation2($bar); return $baz;}

function factoredComputation1($foo) { yield ...; // pseudo-code (something we factored out) yield ...; // pseudo-code (something we factored out) return 'zanzibar';}

function factoredComputation2($bar) { yield ...; // pseudo-code (something we factored out) yield ...; // pseudo-code (something we factored out) return 42;}

Engine Exceptionstry { $o = null; $o->method();} catch (EngineException $e) { echo "Exception: {$e->getMessage()}\n";}

try { eval("Hello GTA-PHP!");} catch (ParseException $e) { echo "Exception: {$e->getMessage()}\n";}

Engine Exceptions

BaseException (abstract) EngineException ParseException Exception ErrorException RuntimeException

(BTW, outside of a try block, calls to a member function of a non-object now raise a non fatal E_RECOVERABLE_ERROR)

Group Use Declarations

use FooLibrary\Bar\Baz\{ ClassA, ClassB, ClassC, ClassD as Fizbo };

use Symfony\Component\Console\{ Helper\Table, Input\ArrayInput, Input\InputInterface, Output\NullOutput, Output\OutputInterface, Question\Question, Question\ChoiceQuestion as Choice, Question\ConfirmationQuestion,};

Uniform Variable Syntax// support missing combinations of operations

$foo()['bar']()[$obj1, $obj2][0]->propgetStr(){0} // support nested ::$foo['bar']::$baz$foo::$bar::$baz$foo->bar()::baz() // support nested ()foo()()$foo->bar()()Foo::bar()()$foo()()

// support operations on arbitrary (...) expressions(...)['foo'](...)->foo(...)->foo()(...)::$foo(...)::foo()(...)() // two more practical examples for the last point(function() { ... })()($obj->closure)() // support all operations on dereferencable scalars (not very useful)"string"->toLower()[$obj, 'method']()'Foo'::$bar

Uniform Variable Syntax

Unicode Escape Syntax

echo "We \u{2665} PHP\n";

We ♥ PHP

Coalesce ??

isset($_GET['user']) ? $_GET['user'] : 'nobody'

$_GET['user'] ?? 'nobody'

“COALESCE, an SQL command that selects the first non-null from a range of

values”- Wikipedia

$x = ["yarr" => "meaningful_value"];echo $x["aharr"] ?? $x["waharr"] ?? $x["yarr"];

Closure::callclass Foo { private $x = 3; }$foo = new Foo;

$foobar = function () { var_dump($this->x); };

$foobar->call($foo); // prints int(3)

Filtered unserialize()// Unserialize everything as before$data = unserialize($foo);

// Convert all objects into __PHP_Incomplete_Class object$data = unserialize($foo, ["allowed_classes" => false]);

//Convert all objects except MyClass / MyClass2 into __PHP_Incomplete_Class$data = unserialize($foo, ["allowed_classes" => [ "MyClass", “MyClass2",]);

//accept all classes as in default$data = unserialize($foo, ["allowed_classes" => true]);

Small Stuff

Turn gc_collect_cycles into function pointer

Remove the date.timezone

warning

Remove E_STRICT in favour of E_DEPRECATED, E_NOTICE, E_WARNING or

removal

Continue output buffering despite

aborted connection

“Fixed” assert()

Better i18n/l10n with IntlChar class

Integer Semantics

intdiv(3, 2); //1

session_start() read_only and lazy_write options

Backwards Compatibility

Breaks

Reserved words: int, float, bool, string, true, false, null

Reserved for future use: resource, object, scalar, mixed,

numeric

Constructor behaviour of internal classes: what returned null now

throws an error

"Remove" PHP 4 constructors with E_DEPRECATED

Much that was deprecated is now GONE - the big one is mysql

Extension API: Big changes, possible “PNI”

Custom session handlers will return true or false,

not 0 (SUCCESS) or 1

(FAILURE)

Remove alternative PHP tags

<% opening tag<%= opening tag with echo%> closing tag(<script\s+language\s*=\s*(php|"php"|'php')\s*>)i opening tag(</script>)i closing tag

Does not remove short opening tags (<?) or short opening tags with echo (<?=).

Bottom line: Modern PHP should work fine

Bug Fixes

foreach$a = [1,2,3]; foreach($a as $v) { echo $v . " - " . current($a) . "\n";}

1 - 22 - 23 - 2

$a = [1,2,3]; $b = $a; foreach($a as $v) { echo $v . " - " . current($a) . "\n";}

1 - 12 - 13 - 1

PHP 7’s foreach doen’t changean array’s internal pointer

Remove hex support in numeric strings

$str = '0x123';if (!is_numeric($str)) { throw new Exception('Not a number');}

$n = (int) $str;

// Exception not thrown, instead the// wrong result is generated here: // 0

Multiple Default Cases in a Switch

switch ($expr) { default: doSomething(); break; default: somethingElse();}

Previously called last default

PHP 7 raises E_COMPILE_ERROR

Fix list() Inconsistency

list($a,$b) = "aa";var_dump($a,$b);

$a[0]="ab";list($a,$b) = $a[0];var_dump($a,$b);

NULLNULL

string(1) "a"string(1) "b"

PHP 7’s list treats strings

like arrays

References

• PHP 7 at a glance: http://devzone.zend.com/4693/php-7-glance/

• What to Expect When You’re Expecting PHP 7: https://blog.engineyard.com/2015/what-to-expect-php-7

• https://wiki.php.net/rfc#php_70https://wiki.php.net/rfc#pending_implementation

Thank-you!