Skip to content
Advertisement

Check if object exist and has property

How can i get something prettier than condition inside condition?

$permission = $user->permissions; //return object with permissions
 if ($permission) {
     if (!$permission->can_edit) {
         throw Errors::exception(Errors::PERMISSION_DENIED);
     }
 }
        

Advertisement

Answer

You can merge your 2 if in the same :

$permission = $user->permissions; //return object with permissions
 if ($permission && !$permission->can_edit){
         throw Errors::exception(Errors::PERMISSION_DENIED);
 }

Because if $permission was false or empty ( not exist ) php not execute the following test !$permission->can_edit then u don’t have errors, and you write 1 if.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement