Skip to content

Instantly share code, notes, and snippets.

@tbreuss
Last active May 1, 2023 08:50
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 tbreuss/17b94b8bd74124ff75039a2b03a380c0 to your computer and use it in GitHub Desktop.
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.
<?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