Skip to content

Instantly share code, notes, and snippets.

@medigeek
Created August 8, 2020 21:18
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 medigeek/d8d48ad1c1181f0b9d9d78866c5731b3 to your computer and use it in GitHub Desktop.
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
<?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