Created
August 8, 2020 21:18
-
-
Save medigeek/d8d48ad1c1181f0b9d9d78866c5731b3 to your computer and use it in GitHub Desktop.
Why is declare(strict_types=1); important -- test with spurious (extra) arguments passed to methods
This file contains hidden or 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 | |
declare(strict_types=1); | |
//see results: | |
//using declare(strict_types=1): https://3v4l.org/XJYlJ | |
//commented out declare(strict_types=1): https://3v4l.org/1bD85 | |
class Fruit { | |
// Properties | |
private string $name; | |
private string $color; | |
// Methods | |
function setName(string $name): string { | |
$this->name = $name; | |
return $name; | |
} | |
// Methods | |
function setColor(string $color): string { | |
$this->color = $color; | |
return $this->color; | |
} | |
function setNameAndColor(string $name, string $color): array { | |
$this->name = $name; | |
$this->color = $color; | |
return [$this->name, $this->color]; | |
} | |
function setNameAndColorAndOptionalBoolean(string $name, string $color, bool $booleanArgument = false): array { | |
$this->name = $name; | |
$this->color = $color; | |
return [$this->name, $this->color]; | |
} | |
function getName(): string { | |
return $this->name; | |
} | |
function getColor(): string { | |
return $this->color; | |
} | |
function getNameAndColor(): array { | |
return [$this->name, $this->color]; | |
} | |
} | |
$testFruit = new Fruit; | |
$methodsArray = [ | |
'setName' => '1arg', | |
'setNameAndColor' => '2args', | |
'setNameAndColorAndOptionalBoolean' => '3args' | |
]; | |
$methodsResults = []; | |
foreach ($methodsArray as $methodName => $methodType) { | |
if ($methodType == '1arg') { | |
printf("%s - %s\n", $methodName, $methodType); | |
$methodsResults[$methodName] = $testFruit->$methodName('Orange1arg', 'spurious argument'); | |
} | |
elseif ($methodType == '2args') { | |
printf("%s - %s\n", $methodName, $methodType); | |
$methodsResults[$methodName] = $testFruit->$methodName('Orange2args', 'orange', true); | |
} | |
elseif ($methodType == '3args') { | |
printf("%s - %s\n", $methodName, $methodType); | |
$methodsResults[$methodName] = $testFruit->$methodName('Orange3args', true, 'orange', true); | |
} | |
} | |
$getNameAndColor = $testFruit->getNameAndColor(); | |
var_dump($testFruit, $methodsResults, $getNameAndColor); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment