Hello, I am working on a PHP exercise: Resistor Color in PHP on Exercism
I am not entirely sure why the solution I am attempting is not working.
In the following code, I have declared the $colorCodes
variable above the functions, and then used the global
keyword to import the global $colorCodes
I have declared.
If I var_dump($colorCodes);
right after the declaration of the variable, it shows me the populated array, however if I do the same inside the getAllColors()
function, I am getting NULL.
declare(strict_types=1);
$colorCodes = array(
'Black' => 0,
'Brown' => 1,
'Red' => 2,
'Orange' => 3,
'Yellow' => 4,
'Green' => 5,
'Blue' => 6,
'Violet' => 7,
'Grey' => 8,
'White' => 9,
);
function getAllColors(): array
{
global $colorCodes;
return array_keys($colorCodes);
}
function colorCode(string $color): int
{
global $colorCodes;
return $colorCodes[$color];
}
When I run ./phpunit ResistorColorTest.php
I get
1) ResistorColorTest::testColors
TypeError: array_keys(): Argument #1 ($array) must be of type array, null given
I cannot see why this is not working when it seems pretty much identical to some of the examples in the PHP Manual: PHP: Variable scope - Manual
Any insight or help is appreciated.