Last active
May 1, 2023 08:50
-
-
Save tbreuss/17b94b8bd74124ff75039a2b03a380c0 to your computer and use it in GitHub Desktop.
PHP (fake) tuples. Tuples are not built in in PHP, but we can create Python like tuples with simple arrays using shorthand array syntax and destructuring.
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 | |
/** | |
* A low-level function for retrieving data. Throws an exception in case of an error. | |
* | |
* @return array | |
*/ | |
function retrieve_data(): array | |
{ | |
// throw an exception in case of an error | |
// throw new Exception('Could not retrieve data.'); | |
return ['apple', 'pear', 'banana']; | |
} | |
/** | |
* A service function to retrieve fruits that returns a tuple with a boolean value and an array. | |
* | |
* @return array{bool, array} | |
*/ | |
function get_fruits(): array | |
{ | |
try { | |
$data = retrieve_data(); | |
} catch (Exception $e) { | |
return [false, [$e->getMessage()]]; // the tuple | |
} | |
return [true, $data]; // the tuple | |
} | |
[$status, $fruitsOrErrors] = get_fruits(); | |
if ($status === true) { | |
[$apple, $banana] = $fruitsOrErrors; | |
echo "We have these fruits: " . join(", ", $fruitsOrErrors) . '.'; | |
} else { | |
[$firstError] = $fruitsOrErrors; | |
echo $firstError; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment