Created
July 24, 2015 18:12
-
-
Save tpunt/ccab636067a3f815dec8 to your computer and use it in GitHub Desktop.
Backporting PHP 7 string type declaration to PHP 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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