Created
June 30, 2016 12:48
-
-
Save mathiasverraes/a0abb8d83f8579dd6a6b2bd850f302b3 to your computer and use it in GitHub Desktop.
PHP string casting
This file contains 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 | |
final class FuckYouPHPTest extends \PHPUnit_Framework_TestCase { | |
/** @test */ | |
public function should_fail () { | |
new WantsAString(new NotAString()); | |
// Fails as expected | |
} | |
/** @test */ | |
public function casting_like_were_still_in_the_PHP4_era () { | |
new WantsAString(new Stringable()); | |
// Silently casts to string. It's consistent with the traditions of the | |
// PHP forefathers, but it is stupid nonetheless and leads to errors. | |
} | |
} | |
final class WantsAString { | |
private $mustBeString; | |
public function __construct (string $mustBeString) { | |
$this->mustBeString = $mustBeString; | |
} | |
} | |
final class NotAString {} | |
final class Stringable { | |
public function __toString () { | |
return "I was casted from Stringable"; | |
} | |
} |
This is to keep libraries backwards compatible when upgrading to 7.x.
if you want this behaviour add the following to your file.
declare(strict_types=1);
For more documentation see: http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict
Thanks, just found that out.
It's silly though, because if you typehint on string, it is not backwards compatible and the declare thing won't make a difference.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"Hey, about this awesome new feature that we just introduced into the language... Can we find a way to make it unusable?"