PHP code example of xp-lang / php-is-operator

1. Go to this page and download the library: Download xp-lang/php-is-operator 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/ */

    

xp-lang / php-is-operator example snippets


is_string($value)                                  // for primitives, use is_[T]()
is_callable($value)                                // for pseudo types callable, array, object
is_array($value) || $value instanceof \Traversable // no is_iterable in PHP 5 and 7.0 
$value instanceof Date                             // for value types
null === $value || is_int($value)                  // nullable types cannot be tested directly
is('[:string]', $value)                            // for types beyond PHP type system
is('string|util.URI', $value)                      // for types beyond PHP type system

$value is string
$value is callable
$value is iterable
$value is Date
$value is ?int
$value is array<string, string>
$value is string|URI

$value is 'test';
$value is 5;
$value is 3|5|null;
$value is 'heart'|'spade';
$value is self::Wild;
$value is 'heart'|'spade'|self::Wild;

$value is <10;
$value is >=5;
$value is >5 & <10;

$value is Point(x: 3);      // Matches any Point whose $x property is 3
$value is Point(x: 4|5);    // Matches any Point whose $x property is 4 or 5
$value is Point(y: 3)|null; // Matches any Point whose $y property is 3, allowing `null`
$value is Point(y: >0);     // Matches any Point whose $x property is greater than 0


$value is [1, 2, 3, 4];     // Exact match
$value is [1, 2, 3, ...];   // Begins with 1, 2, 3, but may have other entries
$value is [1, 2, mixed, 4]; // Allows any value in the 3rd position
$value is [1, 2, 3|4, 5];   // 3rd value may be 3 or 4

$value is ['a' => 'A', 'b' => 'B']; // Exact key/value match, but order doesn't matter
$value is ['b' => 'B', ...];        // Must have a 'b' key with value 'B', and more
$value is ['b' => mixed, ...];      // Must have a 'b' key with any value, and more

$value is Point(x: 3, y: $y);           // If $p->x === 3, bind $p->y to $y
$value is ['a' => 'A', 'b' => $b];      // Bind value of key 'b' to $b
$value is ['op' => 'drop', ... $items]; // Bind rest of array to $items

$result= match ($value) {
  is int    => $value,
  is string => '"'.strtr($value, ['"' => '\\"']).'"',
  null      => 'null',
};