Sunday 5 August 2018

php - Blocks - curly braces/no curly braces?





When I started developing, I followed tutorials that always used {} (curly braces) to enclose blocks. However, when I began looking at other peoples code (classes on GitHub for example, or just more code in general than what a basic tutorial would show), however I've also seen block statements without being enclosed in {}, for example;



if($var < 15)
$string = 'Hello, Jimmy!';
elseif($var >= 15)

$string = 'Hello, Anne!';


Is the same as



if($var < 15) { 
$string = 'Hello, Jimmy!';
} elseif($var >= 15) {
$string = 'Hello, Anne!';
}



I've never used blocks not enclosed in {}, however I used them today and I'm starting to see the efficiency of doing so (it looks a lot cleaner too, as I'll often find my functions riddled with {} from loops, conditionals etc.



What I'm asking is;



a) are there any limitations on blocks without curly braces (; I noticed my IDE dropped back from an indent after I enter a single line and returned after an if() conditional?



b) are there any best practices to be had, when not using {}?




Any answers, specifically those inc. background/docs on the convention of curly brace usage for blocks vs. not using them would be greatly appreciated, as I'd really like to understand the usage of curly braces :)!


Answer



You can omit the {} for one single line:



if(something)
do something else


however you cannot omit it and have it keep going like so:




if(something)
do one thing
do another
do some more


The example above would only have 1 conditional element (the 'do one thing'). The rest would just run unconditionally.



And yes I've seen the sloppy method before without the {}, I myself prefer using {} to separate the logic, and its easier to read.




So stick to using {} in your code.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...