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

"Hey, about this awesome new feature that we just introduced into the language... Can we find a way to make it unusable?"

@jelte
Copy link

jelte commented Jun 30, 2016

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

@mathiasverraes
Copy link
Author

Thanks, just found that out.

@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