Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Created June 30, 2016 12:48
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 mathiasverraes/a0abb8d83f8579dd6a6b2bd850f302b3 to your computer and use it in GitHub Desktop.
Save mathiasverraes/a0abb8d83f8579dd6a6b2bd850f302b3 to your computer and use it in GitHub Desktop.
PHP string casting
<?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";
}
}
@mathiasverraes
Copy link
Author

mathiasverraes commented Jun 30, 2016

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