PHP code example of omitobisam / conditional

1. Go to this page and download the library: Download omitobisam/conditional library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

omitobisam / conditional example snippets


conditional(isset($data))
    ->then(fn() => doThis())
    ->else(fn() => doThat());


use Conditional\Conditional;
$data = null;

Conditional::if(is_null($data))
    ->then(fn() => doThis())
    ->else(fn() => doThat());


conditional(isset($data))
    ->then(fn() => doThis())
    ->else(fn() => doThat());

conditional('1' === 'a', 1, 2); //returns 2 - without calling ->value()

conditional(false, 1)

  ->else(2); //returns 2 - without calling ->value()

// Of course the normal one
conditional(false)

  ->then(1)

  ->else(2); //returns 2

use Conditional\Conditional;

Conditional::if(fn() =>  '1' == 1) // or conditional(fn() => 1 + 1)
    ->then(fn() => doThis()) // doThis() is executed
    ->else(fn() => doThat());

use Conditional\Conditional;

$value = Conditional::if(fn() => 'a' !== 1) // or conditional(fn() => 'a' !== 1)
    ->then(1)
    ->value(); // returns 2 (because a !== 1)

//do something with $value

use Conditional\Conditional;

class Invokable {

    public function __invoke()
    {
        return 'I was Invoked';
    }
}

$invokableClass = new Invokable();

$value = Conditional::if(fn() => 'a' === 1) // or conditional(fn() => 1 + 1)
    ->then(1)
    ->else($invokableClass); //Value returns 'I was Invoked'

// Do something with $value

 \conditional('foo' === 'bar')

    ->then('foo === bar')

    ->else(new TestException('Foo is not the same as bar'));  //this exception is thrown

conditional(isset($data))

    ->then(fn() => doThis())

    ->elseIf(is_int(1))

    ->then(fn() => doThat())

    ->else(2);

$value = Conditional::if(false)

    ->then('a')

    ->elseIf('b' == 1) //first one

    ->then('b')

    ->elseIf('b' !== 2) //another

    ->then('2')

    ->else(1);

// $value is '2'

Conditional::if(is_array('a'), 'ninja') //default value is ninja

    ->then(fn() => doThis())

    ->elseIf(is_int(""))

    ->then(fn() => doThat())
    
    ->value(); // 'ninja' is returned :scream:

// This is Wrong!

Conditional::if(true)
    ->then(1)
    ->else(2)
    ->if('1'); // Don't do it except you intend to start a new and fresh if Conditional