April 14, 2018 —John Koster
The throw_unless
helper function is the logical counterpart to the throw_if
helper function. If the provided $boolean
value evaluates to false
, a new instance of the provided exception will be created and thrown. Any parameters specified will be passed to the exceptions constructor when it is instantiated.
The signature of the throw_unless
function is:
1function throw_unless(2 $boolean,3 $exception,4 ...$parameters5);
In the following example we rewrite the throw_if
example to use the throw_unless
function. This example function will throw an exception when the supplied $value
is equal to 10
.
1 2function throwUnlessExample($value) { 3 throw_unless( 4 $value != 10, 5 Exception::class, 6 'The value must not be 10!' 7 ); 8 9 // Do something with the value when it is not 10.10}11 12// Will not throw an exception.13throwUnlessExample(3);14 15// Will throw an exception.16throwUnlessExample(10);
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.