Skip to content

Instantly share code, notes, and snippets.

@RobDWaller
Created April 16, 2018 06:42
Show Gist options
  • Save RobDWaller/6c4b1d4e8a33032578d41cfe99f35bad to your computer and use it in GitHub Desktop.
Save RobDWaller/6c4b1d4e8a33032578d41cfe99f35bad to your computer and use it in GitHub Desktop.
PHP return types will cast variable types if setup wrong
<?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