Created
April 16, 2018 06:42
-
-
Save RobDWaller/6c4b1d4e8a33032578d41cfe99f35bad to your computer and use it in GitHub Desktop.
PHP return types will cast variable types if setup wrong
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 | |
/** | |
* In PHP if you don't turn on strict types return types will interpret and | |
* cast variable types. For example the integer 123 if returned from a method | |
* with a return type of string will return '123'. | |
* | |
* Always turn on strict types in your application. | |
* | |
* declare(strict_types = 1); | |
*/ | |
class ReturnType | |
{ | |
private $number; | |
public function __construct(int $number) | |
{ | |
$this->number = $number; | |
} | |
public function getNumber(): string | |
{ | |
return $this->number; | |
} | |
} | |
$number = 123; | |
// This will output 'string' | |
var_dump(gettype($number)); | |
$returnType = new ReturnType($number); | |
$number = $returnType->getNumber(); | |
// This will output 'integer' | |
var_dump(gettype($number)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment