note 125203 deleted from control-structures.goto by salathe
| From: | salathe@php.net | Date: | Mon, 21 Sep 2020 14:42:47 +0000 |
| Subject: | note 125203 deleted from control-structures.goto by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215282@lists.php.net to get a copy of this message | ||
Note Submitter: sisisisi
----
Another good usage of goto statements that don't spoil the readability of code is to go to
return on fail conditions if you want to return error code and data.
<?php
function editItem($id, $fields)
{
$error_code = 0;
$data = null;
if(!is_numeric($id))
{
$error_code = 1;
goto end;
}
if(!is_array($fields) || !isset($fields["mandatory_field"])
{
$error_code = 2;
goto end;
}
$db->update($id, $fields);
if($db->error())
{
$error_code = 3;
goto end;
}
$data = $db->results() // might be any value
return
[
"error_code" => $error_code,
"data" => $data
];
}
?>
This is
- much more readable than nesting the ifs:
<?php
function foo($id, $fields)
{
$error_code = 0;
$data = null;
if(!failcondition1)
{
if(!failcondition2)
{
if(!failcondition3)
{
...
}
else
{
$error_code = 3;
}
}
else
{
$error_code = 2;
}
}
else
{
$error_code = 1;
}
return [ "error_code" => $error_code, "data" => $data ];
}
?>
- much less error prone than returning the result array on every error (you cannot misspell the
keys):
<?php
function foo($id, $fields)
{
if(failcondition1)
{
return [ "error_code" => 1, "data" => null ];
}
if(failcondition2)
{
return [ "error_code" => 2, "data" => null ];
}
if(failcondition3)
{
return ["errorr_code" => 3, "data" => null ]; // oops
}
// do stuff
?>
- doesn't accidentally mistake a valid return value for an error (in case you don't use a
result array with error code
<?php
function foo($bar, $baz)
{
if(failcondition1)
return false;
if(failcondition2)
return false;
if(failcondition3)
return false;
return dostuff($bar) && otherstuff($baz); // false
}
?>