Skip to content

Instantly share code, notes, and snippets.

@tpunt
Created July 24, 2015 18:12
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 tpunt/ccab636067a3f815dec8 to your computer and use it in GitHub Desktop.
Save tpunt/ccab636067a3f815dec8 to your computer and use it in GitHub Desktop.
Backporting PHP 7 string type declaration to PHP 5
<?php
// in coercive mode
// PHP 7 func
function foo(string $bar)
{
return $bar;
}
// PHP 5 func equiv
function baz($qux)
{
if (!is_string($qux)) {
if (is_int($qux) || is_float($qux) || is_bool($qux)) {
$qux = (string) $qux;
} elseif (is_object($qux) && method_exists($qux, '__toString')) {
$qux = $qux->__toString();
} else {
throw new Exception;
}
}
return $qux;
}
class Test {function __toString() {return 'a';}}
var_dump(foo(1));
var_dump(foo(1.1));
var_dump(foo(true));
var_dump(foo(new Test));
var_dump(foo(new StdClass)); // error
var_dump(foo(null)); // error
var_dump(foo(fopen(__FILE__, 'r'))); // error
var_dump(baz(1));
var_dump(baz(1.1));
var_dump(baz(true));
var_dump(baz(new Test));
var_dump(baz(new StdClass)); // error
var_dump(baz(null)); // error
var_dump(baz(fopen(__FILE__, 'r'))); // error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment