I noticed in WordPress, for example, that there are multiple if statements with blank returns before the action is performed:
function save_book_meta($post_id) {
$slug = 'book';
if($slug != $_POST['post_type']) {
return;
}
if(!current_user_can('edit_post', $post_id)) {
return;
}
// perform actions here
}
What is the difference between writing it like that and writing it like in the example below, where instead of returning nothing it does the checks, and then performs the action:
function save_book_meta($post_id) {
$slug = 'book';
if($slug == $_POST['post_type'] && current_user_can('edit_post', $post_id)) {
// perform actions here
}
}
My questions are:
- What is the purpose of the blank return?
- Is that a good practice to have multiple return statements (even though only one will be executed) or should the return ideally be at the end of the function?
ifconditions in this case would be to prevent unnecessary processing (hitting the DB and performing business logic to determine the user’s permission levels). If you can determine aFALSEresult with as little effort as possible from the beginning, there is no point in continuing to perform more complex tests.Generally though I would probably join 2 simple conditions. But in this case, I think it’s appropriate.