Skip to content

Instantly share code, notes, and snippets.

@koshiaaaaan
Created November 2, 2010 08:00
Show Gist options
  • Save koshiaaaaan/659359 to your computer and use it in GitHub Desktop.
Save koshiaaaaan/659359 to your computer and use it in GitHub Desktop.
switch( true ) のやつ
<?php
$a = 1 ;
switch( true ) {
case ( is_string( $a ) ) :
echo '$a は 文字列' ;
break ;
case ( is_integer( $a ) ) :
echo '$a は 数値' ;
break ;
case ( is_array( $a ) ) :
echo '$a は 配列' ;
break ;
default :
echo '$a は 不正な型です' ;
break ;
}
<?php
class Peta_SwitchSample
{
public function __call( $method, $args )
{
if( $method !== 'bar' ) {
throw new Exception( 'Call to undefined method ' . __CLASS__ . '::' . $method . '()' ) ;
}
switch( count( $args ) ) {
case 0 :
return $this->{ $method . 'Case0' }() ;
case 1 :
switch( true ) {
case ( is_string( $args[ 0 ] ) ) :
return $this->{ $method . 'Case1' }( $args[ 0 ] ) ;
case ( is_integer( $args[ 0 ] ) ) :
return $this->{ $method . 'Case2' }( $args[ 0 ] ) ;
default :
break ;
}
case 2 :
switch( true ) {
case ( is_integer( $args[ 0 ] ) && is_bool( $args[ 1 ] ) ) :
return $this->{ $method . 'Case3' }( $args[ 0 ], $args[ 1 ] ) ;
default :
break ;
}
default :
break ;
}
throw new Exception( 'Arguments are not supported' ) ;
}
private function barCase0()
{
return 'sampleCase0' ;
}
private function barCase1( $str )
{
return 'sampleCase1' ;
}
private function barCase2( $int )
{
return 'sampleCase2' ;
}
private function barCase3( $int, $bool )
{
return 'sampleCase3' ;
}
}
$sample = new Peta_SwitchSample() ;
try {
echo $sample->bar( 'string' ) ;
} catch( Exception $e ) {
echo '<pre>' . $e . '</pre>' ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment