note 125203 added to control-structures.goto
| From: | sisisisi@php.net | Date: | Fri, 24 Jul 2020 10:26:20 +0000 |
| Subject: | note 125203 added to control-structures.goto | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214885@lists.php.net to get a copy of this message | ||
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
}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.167.36 (proxied: 194.149.32.5)
----
Manual Page -- http://php.net/manual/en/control-structures.goto.php
Edit -- https://master.php.net/note/edit/125203
Del: integrated -- https://master.php.net/note/delete/125203/integrated
Del: useless -- https://master.php.net/note/delete/125203/useless
Del: bad code -- https://master.php.net/note/delete/125203/bad+code
Del: spam -- https://master.php.net/note/delete/125203/spam
Del: non-english -- https://master.php.net/note/delete/125203/non-english
Del: in docs -- https://master.php.net/note/delete/125203/in+docs
Del: other reasons-- https://master.php.net/note/delete/125203
Reject -- https://master.php.net/note/reject/125203
Search -- https://master.php.net/manage/user-notes.php