Slide 1

Slide 1 text

PHP 7.1 - Iterable and Void New Types For Typecasting August 2016

Slide 2

Slide 2 text

iterable (it-ah-ah-bul) This is a multi-type type which includes any objects which implement the Traversable interface, as well as arrays. It means the function can accept or return a value which will work with the looping constructs.

Slide 3

Slide 3 text

// arrays are iterable. $Stuff = [ 1, 2, 3 ];

Slide 4

Slide 4 text

// objects implementing Iterator are iterable. class Pile implements Iterator { public function Current() { /* ... */ } public function Key() { /* ... */ } public function Next() { /* ... */ } public function Rewind() { /* ... */ } public function Valid() { /* ... */ } }

Slide 5

Slide 5 text

// generators are iterable. function ImAnGenerator() { for($A = 1; $A <= 3; $A++) { yield $A; }

Slide 6

Slide 6 text

// process iterables. function CanHasIter(Iterable $Stuff): Void { if(is_array($Stuff)) echo 'by array', PHP_EOL; else printf('by %s%s', get_class($Stuff), PHP_EOL); echo '> '; foreach($Stuff as $Thing) echo $Thing, ' '; echo PHP_EOL; return; }

Slide 7

Slide 7 text

$Stuff = [ 'omg','wtf','bbq' ]; $Pile = (new Pile)->SetData($Stuff); // give it a direct array. CanHasIter([1, 2, 3]); // give it an array variable. CanHasIter($Stuff); // give it an iterable object. CanHasIter($Pile); // give it an iterable object. CanHasIter($Pile->StartsWithVowel()); // give it a generator. CanHasIter(ImAnGenerator()); // give it a string. (intentional error) CanHasIter('omfg');

Slide 8

Slide 8 text

C:\~\Desktop\PHP71> php Code\Iterable.php by array > 1 2 3 by array > omg wtf bbq by Pile > omg wtf bbq by Pile > omg by Generator > 1 2 3 Fatal error: Uncaught TypeError: Argument 1 passed to CanHasIter() must be iterable, string given

Slide 9

Slide 9 text

void (voyyyyy-duh) This is a restrictive type which declares "this function returns nothing." aka "i does things, not give things" It means so much nothing that even `return NULL` is not valid. Function must EOB or end with a flat with `return;` Can only be used as a return type, not an argument type.

Slide 10

Slide 10 text

// void: hitting the eob without return function TotallyVoid(): Void { /* ... */ }

Slide 11

Slide 11 text

// void: returning absolutely nothing. function AlsoTotallyVoid(): Void { /* ... */ return; }

Slide 12

Slide 12 text

// fail: returning anything, even NULL. function InvoidableFail(): Void { /* ... */ return NULL; }

Slide 13

Slide 13 text

C:\~\Desktop\PHP71> php Code\Void.php Fatal error: A void function must not return a value (did you mean "return;" instead of "return null;"?)

Slide 14

Slide 14 text

@DallasPHP @bobmagicii Code: https://github.com/bobmagicii/dallasphp-201608-php71-iterable-void Slides: https://speakerdeck.com/bobmajdakjr/php-7-dot-1-iterable-and-void