Introduction | Installation | Usage | Credits | Contributing
Following a discussion on Twitter between Christopher Miller and Wendell Adriel around the lack of strongly typed inline variables for PHP we quickly decided a package was the right approach whilst we could get an RFC into the core.
This is that package! you can now control the types of internal vars using a couple of different patterns.
For now, it is only single type or nullable single type, union types coming soon!
You can install the package via composer:
composer require strictus/strictus
There are a few different patterns you can use to work with this package.
You will need to use the Strictus
class (use Strictus\Strictus;
) in any class you wish to use this.
You can then strictly type a variable with any of the below methods:
Type | Nullable | Method |
---|---|---|
String | No | Strictus::string($value) |
String | Yes | Strictus::string($value, true) |
String | Yes | Strictus::nullableString($value) |
Integer | No | Strictus::int($value) |
Integer | Yes | Strictus::int($value, true) |
Integer | Yes | Strictus::nullableInt($value) |
Float | No | Strictus::float($value) |
Float | Yes | Strictus::float($value, true) |
Float | Yes | Strictus::nullableFloat($value, true) |
Boolean | No | Strictus::boolean($value) |
Boolean | Yes | Strictus::boolean($value, true) |
Boolean | Yes | Strictus::nullableBoolean($value) |
Array | No | Strictus::array($value) |
Array | Yes | Strictus::array($value, true) |
Array | Yes | Strictus::nullableArray($value) |
Object | No | Strictus::object($value) |
Object | Yes | Strictus::object($value, true) |
Object | Yes | Strictus::nullableObject($value) |
Class Type | No | Strictus::instance($instanceType, $value) |
Class Type | Yes | Strictus::instance($instanceType, $value, true) |
Class Type | Yes | Strictus::nullableInstance($instanceType, $value) |
Once you have your typed variables created, you have two options on how to use them.
You can get the variable value using it like a function:
$myString = Stricuts::string('Hello');
$myString(); // Hello
You can also use it like a Value Object:
$myString = Stricuts::string('Hello');
$myString->value; // Hello
You can update the variable value using it like a function:
$myString = Stricuts::string('Hello');
$myString('Hello, world');
$myString(); // Hello, world
You can also use it like a Value Object:
$myString = Stricuts::string('Hello');
$myString->value = 'Hello, world';
$myString->value; // Hello, world
If you try to assign a value that doesn't match the type of the created variable, an
Strictus\Exceptions\StrictusTypeException
exception will be thrown:
$myString = Stricuts::string('Hello');
$myString(1); // StrictusTypeException
$myString->value = false; // StrictusTypeException
All PRs are welcome.
For major changes, please open an issue first describing what you want to add/change.