Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel
Last active September 28, 2018 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeschinkel/6d986e74285fa27747388c67c2e3d0e7 to your computer and use it in GitHub Desktop.
Save mikeschinkel/6d986e74285fa27747388c67c2e3d0e7 to your computer and use it in GitHub Desktop.
Potential Union Types in PHP
<?php
// Class version:
$tf = new ThingFinder()
$thing = $tf->find( new IntOrString( 123 ) )
// or
$thing = $tf->find( new IntOrString( "foo" ) )
// or
$thing = $tf->find( new IntOrString( true ) ) // Throws undefined thing error, or returns null.
// Versus "Union" version:
$tf = new ThingFinder()
$thing = $tf->find( 123 )
// or
$thing = $tf->find( foo )
// or
$thing = $tf->find( true ) // Throws "not an int or string" error.
<?php
class intOrString {
public $value;
function __construct( $value ) {
$this->value = $value;
}
function toInt(): int {
return (int)$this->value;
}
function toString(): string {
return (string)$this->value;
}
function type(): string {
return is_int( $this->value )
? 'int'
: 'string';
}
}
union intOrString {
int
string
}
class Thing {
}
class ThingFinder {
function find( intOrString $id ): Thing {
switch ( $id->type() ) {
case 'int':
$thing = $this->findByInt( $id->toInt() );
break;
default:
$thing = $this->findByString( $id->toString() );
break;
}
return $thing;
}
function altFind( intOrString $id ): Thing {
if ( is_null( $thing = $this->findByInt( $id->toInt() ) ) ) {;
$thing = $this->findByString( $id->toString() );
}
return $thing;
}
function findByInt( int $id ): Thing {
return new Thing();
}
function findByString( string $id ): Thing {
return new Thing();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment