https://github.com/conceptbyte/null-object
A silent null object for PHP
https://github.com/conceptbyte/null-object
null nullobject php
Last synced: 3 months ago
JSON representation
A silent null object for PHP
- Host: GitHub
- URL: https://github.com/conceptbyte/null-object
- Owner: conceptbyte
- License: mit
- Created: 2016-07-25T09:09:09.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2016-07-25T09:22:15.000Z (over 9 years ago)
- Last Synced: 2025-05-09T21:14:36.352Z (11 months ago)
- Topics: null, nullobject, php
- Language: PHP
- Size: 3.91 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Null Object for PHP
Allows the user to call the null object which handles all calls silently and returns sensible defaults.
The returned object can be type cast to return the following values:
- String - ""
- Integer - 0
- Float or Real - 0.0
- Array - []
- Boolean - False
## Installation
Run the following to install:
```composer require conceptbyte/null-object```
## Usage
The null object can be created in one of the following methods:
- Named constructor: ```NullObject::create()```
- Helper function: ```no()```
Both will return an instance of the class.
Calls to any methods or members on this class will return
the defaults as mentioned in the section above.
## Example
```php
(string) NullObject::create()->xyz; // ""
(bool) NullObject::create()->abc(); // false
(int) no()->xyz; // 0
(float) no()->abc(); // 0.0
```
## Quirks
PHP does not allow modifying the behaviour of casting a class to boolean.
A simple hack is to use the SimpleXMLElement class which can return false when passed
an empty XML tag.