Slide 1

Slide 1 text

PHP 7.1 - Nullable Taking the edge off hard types. September 2016

Slide 2

Slide 2 text

nullable (nawl-lahblah) PHP's 7.0 type system adds rigidity to function arguments and return values with, no exception. Nullables re-add some flexibility afforded by PHP OOP in 7.1. "It can return this type, or null" "I can take this type, or null"

Slide 3

Slide 3 text

// this function only accepts ints. public function EatAllTheInts(Int $Number): Void { // ... }

Slide 4

Slide 4 text

// this function only returns Nether\Object\Datastore public function GiveAllTheStorage(): Nether\Object\Datastore { // ... };

Slide 5

Slide 5 text

protected $Multiplier = 1.0; public function ModMultiplier(?Float $Value): Float { /*// modify the experience multiplier by the given amount, or reset to default on null. returns the updated value. //*/ if($Value !== NULL) // modify return $this->Multiplier += $Value; else // quiñonify return $this->Multiplier = 1.0; }

Slide 6

Slide 6 text

// buff xp gains. $Character->Experience->ModMultiplier(2.0); // reset xp gain to the standard rate. $Character->Experience->ModMultiplier(NULL);

Slide 7

Slide 7 text

static public function GetByID(Int $ID): ?self { $Result = (new Nether\Database) ->NewVerse() ->Select('dma_objects') ->Fields('*') ->Where('obj_id=:ID') ->Limit(1) ->Query([ 'ID' => $ID ]); if(!$Result->IsOK()) throw new Exception('db exploded'); if(!$Result->GetCount()) return NULL; return new self($Result->Next()); }

Slide 8

Slide 8 text

// display a user profile if found. $User = User::GetByID($Input->ID); if(!$User) return $Request ->Respond(404) ->Body(new NotFoundPage()); else return $Request ->Respond(200) ->Body(new UserProfilePage($User));

Slide 9

Slide 9 text

null coalescing (nawl-coal-sing) Chain NULL checks. Similar to the `or` operator but strict typing to only fall through on NULL.

Slide 10

Slide 10 text

// find something that is not legit null... $Thing = $That ?? $Those ?? $These ?? $Them;

Slide 11

Slide 11 text

// procedural generate characters. // actual code from No Man's Sky. // generate a scientific name for a wild beast to spawn. $Name = ucwords(implode(' ',array_map(function($Part){ return implode('',array_map(function(){ return chr((rand(97,122))); },$Part)); },[array_fill(0,rand(5,9),NULL),array_fill(0,rand(8,16),NUL L)]))); $Thing = Animal::GetByName($Name) ?? Animal::Create($Name); // not actual code from No Man's Sky.

Slide 12

Slide 12 text

@DallasPHP @bobmagicii Slides: https://speakerdeck.com/bobmajdakjr/php-7-dot-1-nullable