Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PHP 7.1 - Nullable

Bob Majdak Jr
September 13, 2016

PHP 7.1 - Nullable

An overview of the types being nullable and stacking that with a null coalesce operator for fun.

Bob Majdak Jr

September 13, 2016
Tweet

More Decks by Bob Majdak Jr

Other Decks in Programming

Transcript

  1. 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"
  2. 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; }
  3. // buff xp gains. $Character->Experience->ModMultiplier(2.0); // reset xp gain to

    the standard rate. $Character->Experience->ModMultiplier(NULL);
  4. 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()); }
  5. // 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));
  6. null coalescing (nawl-coal-sing) Chain NULL checks. Similar to the `or`

    operator but strict typing to only fall through on NULL.
  7. // find something that is not legit null... $Thing =

    $That ?? $Those ?? $These ?? $Them;
  8. // 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.