Skip to content

Instantly share code, notes, and snippets.

@thefuxia
Created August 30, 2013 13:09
Show Gist options
  • Save thefuxia/6389675 to your computer and use it in GitHub Desktop.
Save thefuxia/6389675 to your computer and use it in GitHub Desktop.
Simple Type Casting in PHP
<?php # -*- coding: utf-8 -*-
header( 'Content-Type: text/plain;charset=utf-8' );
interface Simple_Type
{
public function __construct( $var );
public function __get( $var );
}
abstract class Simple_Type_Base implements Simple_Type
{
protected $var;
public function __construct( $var )
{
$this->var = $this->cast( $var );
}
public function __get( $var )
{
return $this->var;
}
abstract protected function cast( $var );
}
class Int extends Simple_Type_Base
{
protected function cast( $var )
{
return (int) $var;
}
}
class Float extends Simple_Type_Base
{
protected function cast( $var )
{
return (float) $var;
}
}
class String extends Simple_Type_Base
{
protected function cast( $var )
{
return (string) $var;
}
}
class Test
{
public $string, $float, $int;
public function take_string( String $string )
{
$this->string = $string->s;
}
public function take_float( Float $float )
{
$this->float = $float->f;
}
public function take_int( Int $int )
{
$this->int = $int->i;
}
}
$string = new String( 1 );
$float = new Float( 1.5 );
$int = new Int( 1.0 );
$test = new Test;
$test->take_string( $string );
$test->take_float( $float );
$test->take_int( $int );
$result = get_object_vars( $test );
var_dump( $result );
/*
array(3) {
["string"]=>
string(1) "1"
["float"]=>
float(1.5)
["int"]=>
int(1)
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment