Skip to content

Instantly share code, notes, and snippets.

@codenamegary
Last active January 4, 2016 09:48
Show Gist options
  • Save codenamegary/8604032 to your computer and use it in GitHub Desktop.
Save codenamegary/8604032 to your computer and use it in GitHub Desktop.
Scalar Type Hinting in PHP
<?php
// See: http://nikic.github.io/2012/03/06/Scalar-type-hinting-is-harder-than-you-think.html
// And RFC: https://wiki.php.net/rfc/scalar_type_hinting_with_cast
//
// Basically the same implementation as outlined in the RFC but with a concept for scalar
// magic to be added to objects at some point in the future.
class MyObjectWithScalarMagic {
public function __toInt()
{
return 1;
}
public function __toFloat()
{
return 1.4;
}
public function __toBool()
{
return false;
}
public function __toResource()
{
return $this->resource;
}
public function __toObject()
{
return $this;
}
public function __toArray()
{
return (array)$this;
}
// Already implemented
public function __toString()
{
return $this->name;
}
}
class MyObjectWithoutScalarMagic {
}
$withMagic = new MyObjectWithScalarMagic;
$withoutMagic = new MyObjectWithoutScalarMagic;
function testInt(int $number)
{
// Always an int
var_dump($number);
}
function testFloat(float $number)
{
// Always a float
var_dump($number);
}
testInt((int) $withMagic); // int(1)
testInt(5); // int(5)
testInt(5.0); // int(5)
testInt("5"); // int(5)
testInt(5.3); // fatal error: int expected, float given
testInt(array()); // fatal error: int expected, array given
testInt("word up"); // fatal error: int expected, array given
testInt($withoutMagic); // fatal error: object could not be converted to integer
testFloat((float) $withMagic); // float(1.4)
testFloat(5); // float(5.0)
testFloat(5.0); // float(5.0)
testFloat("5"); // float(5.0)
testFloat(5.3); // float(5.3)
testFloat(array()); // fatal error: float expected, array given
testFloat("word up"); // fatal error: float expected, string given
testFloat($withoutMagic); // fatal error: object could not be converted to float
// (etc.)
// Also enables the casting functionality you'd expect
var_dump((int) $withMagic); // int(1)
var_dump((float) $withoutMagic); // fatal error: object could not be converted to float
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment