On 4/21/2016 1:00 PM, Lin Yo-An wrote: > I think this is not to make PHP like Java, and it totally makes sense - > Nullable should be a type of a type instead of a state. In Haskell it's > named Maybe or Option, and It's better than NullPointerException. > > Here is a discussion from Haskell community: > https://mail.haskell.org/pipermail/haskell-cafe/2011-April/091269.html >
Why is it /better/? final class None {} final class Some { public $value; public function __construct($value) { $this->value = $value; } } final class Maybe { private static $none; private $value; private function __construct($value) { $this->value = $value; } public static function NOTHING() { if (self::$nothing === null) { self::$nothing = new Nothing(); } return new static(self::$nothing); } public static function SOME($value) { return new static(new Some($value)); } public function hasSome(): bool { return $this->value !== static::$none; } public function isNone(): bool { return $this->value === static::$none; } public function unwrap() { if ($this->value === static::$none) { trigger_error('NullPointerException', E_USER_ERROR); } return $this->value->value; } } // ---------------------------------------- function f1(): Option {} $x = f1(); if ($x->hasSome()) { echo $x->unwrap(); // 42 } $x = f1(); if ($x->isNone()) { echo -1; } echo f1()->unwrap(); // error: NullPointerException :P // ---------------------------------------- function f2(): ?int {} $y = f2(); if (isset($y)) { echo $y; // 42 } $y = f2(); if ($y === null) { echo -1; } echo f2(); // null You can easily build your own Option or Maybe and add the additional bookkeeping to your runtime but it will not make your program more secure or anything. It just adds more method calls and makes it more verbose. You can already use static code analyzers to detect if null is being ignored in your code, however, right now they mainly have to rely on PhpDoc that is often not properly documented. Adding an explicit syntax to PHP for documentation would make PhpDoc obsolete and allow static code analyzers to perform their job better and PHP to error out during runtime if something else is being returned. Honestly, null is not our problem. Every language has its null, just because they wrap it or rename it does not make null suddenly vanish from the universe. :P -- Richard "Fleshgrinder" Fussenegger
signature.asc
Description: OpenPGP digital signature