Created
August 26, 2017 17:17
-
-
Save quant61/8618d0454fbe8acc5a0b5eb4948418d4 to your computer and use it in GitHub Desktop.
SafeNullClass.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: kwant | |
* Date: 26.08.17 | |
* Time: 19:50 | |
* | |
* attempt to create NullObject in php | |
* this object does nothing | |
* also this object doesn't throw any error | |
* | |
* | |
*/ | |
class SafeNullClass implements Countable, IteratorAggregate, ArrayAccess, JsonSerializable | |
{ | |
public function __construct(){} | |
function __call($name, $arguments){} | |
public static function __callStatic($name, $arguments){} | |
function __get($name){} | |
function __set($name, $value){} | |
function __isset($name) | |
{ | |
return false; | |
} | |
function __unset($name){} | |
function __toString() | |
{ | |
return ""; | |
} | |
function __invoke(){} | |
public function getIterator() | |
{ | |
return new EmptyIterator(); | |
} | |
public function offsetExists($offset) | |
{ | |
return false; | |
} | |
public function offsetGet($offset){} | |
public function offsetSet($offset, $value){} | |
public function offsetUnset($offset){} | |
public function count() | |
{ | |
return 0; | |
} | |
function jsonSerialize() | |
{ | |
return null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: kwant | |
* Date: 26.08.17 | |
* Time: 20:11 | |
* | |
* recursive version of NullObject | |
* you can also write someting like | |
* $null->property->getIt()['key']->yay()['x']; | |
* without getting any errors | |
* | |
*/ | |
class SafeNullClassRecursive extends SafeNullClass | |
{ | |
public function __get($name) | |
{ | |
return $this; | |
} | |
public function offsetGet($offset) | |
{ | |
return $this; | |
} | |
public function __call($name, $arguments) | |
{ | |
return $this; | |
} | |
public function __invoke() | |
{ | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment