I've seen a lot of code recently formatted as the following:
A:
if ($var=='test'){
$var=Foo('blah'.$var1);
}else{
// do something
}
Personally I don't like it and would prefer it as:
B:
if ($var == 'test') {
$var = Foo('blah' . $var1);
} else {
// do something
}
I think it's much more readable (note the addition of spaces).
Is there a general preference in the community or is one way better than another?
The most important thing is to follow a standard and stick to it.
That said maybe you can follow Zend's Framework standards and they use spaces. Check C.4.6.
if ($a != 2) {
$a = 2;
}
Hope it helps!
+1 for spaces :)
but that's just my own standard, as long as you are consistent and your code is clear, it should be okay
PHP is much like C in its syntax. As I use both, I tend to follow the same style.
For instance, keywords vs functions:
if ($foo) {
vs
MySuperDuperFunction($foo);
Then you come to a question of indentation:
switch ($bar) {
case CONSTANT:
more_code();
.. is much easier to read as
switch ($bar) {
case CONSTANT:
more_code();
This indicates that the switch and the case are on the same level, which they are. It also helps avoid crazy indentation in yet-to-be-optimal switches.
Your style should illustrate the syntactic sugar of the language you are using. This gets strange with PHP as well as C, because both have forgiving parsers.
If you write something like this:
if($a==2&&b==1&&c>3)
{
I'm going to hunt you down and demand that you pay for my aspirin. The same would go for this:
if (
a==2
&&
b==1
&&
c>3
)
{
... For God sakes man, its not LISP!
It's a matter of convetions that are stablished within your team.
The most famous conventions are Zend Framework and PEAR. You can also create your own, just make sure it is readible.
Personally, I use spaces.
The general advice would be to standardize the code formating, so it meets some best practices, and is widely known, instead of inventing something custom.
PSR-2, the coding style guide would be the best well known approach, accepted by many. here are facts, why it's good to keep the code formatting.
Related
In general, is code length affective to the speed of the program? I'm talking about differences in small sizes not comparing 10,000 lines to 10.
Example #1:
// Ternary Operator
$todo = (empty($_POST['todo'])) ? 'default' : $_POST['todo'];
VS
// The above is identical to this if/else statement
if (empty($_POST['todo'])) {
$action = 'default';
} else {
$action = $_POST['todo'];
}
And other examples like not using common brackets and universal indentation.
Example #2:
if ($gollum === 'halfling') {
$height --;
}
VS
if ($gollum === 'halfling') $height --;
Also using CamelCase naming convention will lower the characters length, is that effective at all? I doubt this is effective, but still it uses less characters.
Cheers!
In your first example, you are using two different constructs, namely the 'ternary operator' and an 'if / else' statement.
Since the 'if / else' statement is more general (ie you can do more thing with it), the compiler / parser will have more difficulties to optimize it. So I would say that the ternary operator might be a little bit faster.
In the second example, it is only about coding style, both codes will probably be compiled / parsed to exactly the same thing, so no gain here.
However, premature optimization is the root of all evil ! The gain from doing such micro tiny optimization, even on a whole application will probably be negligible and will most of the time be at the expense of readability and maintainability. So I would strongly advice against that kind of thing.
Concerning characters length, it won't matter at all, the compiler / parser will transform that anyway to some other representation that could be understood by the computer, so the only thing that will change is the space that your source code will take on the hard drive.
Just write your code the way it is easier for you to understand and let the compiler / parser do those kind of thing. It is much better to optimize the algorithm itself than the way of writing it.
I think you shoud concern coding style more than efficiency now.
if you already have a style guide, follow it. if you not, you can find one or create one. There aren't such difference between your codes both of two examples. You can pick anyone to create your own style guide.
I found in some code snippets something like (the code itself is not important):
if (FALSE === ($thisVariable = $thisOtherVariable)) { ... }
Whereas Im used to do it the other way around:
if (($thisVariable = $thisOtherVariable) === FALSE) { ... }
And I'm just wondering if there is a difference/benefit about using one of the two ways.
Thanks
There is no difference. Moreover, you can reduce the code to
if (!($this->result_id = $this->simple_query($sql)))
As hek2mgl wrote I prefer using false on right side :) which is right ;P heh
there are good code conventions for php
Zend Conventions(Check paragraph If/Else/Elseif)
PEAR Conventions
No, there is no benefit from that. Both are logically the same. It's just a type of a coding convention because some prgrammers think that it has a better readability for them. I prefer the (oldskool) style $a === FALSE as you
Note that PHP CodeSniffer is a powerful tool to check your code against various coding conventions like PEAR, Zend, ... You can also modify them or create your own convention using xml files and a variable rule framework. This will boost the quality and the visual quality of your code! (while it is fun :)
I'm creating a simple application using the Kohana PHP framework, just FYI. This is my first time with the framework.
While developing classes or functions I'm commenting my code using DocBlock. How should I comment my code while using the framework? I meant to code some parts of the code, not whole controllers.
Basically, I'm using following methods:
// Check if variable_name is greater than zero
if($this->var > 0) {
// do something
} else {
// do something
}
if( $result ) {
// display confirmation message
} else {
// display errors
}
Am I doing it right way? Is there a standard for inserting comments in the code?
I'm not using comments like "check if variable is greater than zero". I'm just wondering if is it good practice to put comments into the code.
Not related to visual style of the comments, but a comment like "Check if variable_name is greater than zero" is a bad comment in and by itself. All it does is duplicate the information on the line below. The code should contain names on variables, functions and other things that can be read to know what's going on.
Other than that, I see nothing wrong with the double-slash-comment types.
// Check if variable_name is greater than zero
Such comments are worthless. I only know little PHP, and even if I didn't knew anything about it, I could immediately tell (or at least, very confidently guess) that after looking at the line.
As a general (language-agnostic) rule of thumb, write code that is mostly self-documenting (by using descriptive names, avoiding non-obvious shortcuts, etc.) and only comment why you do something which looks wrong/strange.
Personally, I document inline sparingly (I do religiously put doc-blocks in for methods, classes and member variables though). I believe that code itself should be as self documenting as possible.
There will be times where you need to do something non-obvious or possibly even counter-intuitive. That's the time for inline comments. Try to explain not what the block of code does, but why it does it that way.
There's a great example in Phing's CodeCoverageReportTask class:
// Strange PHP5 reflection bug,
// classes without parent class or implemented interfaces
// seem to start one line off
if ($reflection->getParentClass() == NULL
&& count($reflection->getInterfaces()) == 0)
{
unset($coverageInformation[$classStartLine + 1]);
}
else
{
unset($coverageInformation[$classStartLine]);
}
And another good one just a few lines down from that:
// PHP5 reflection considers methods of a parent class to be part
// of a subclass, we don't
if ($method->getDeclaringClass()->getName() != $reflection->getName())
{
continue;
}
I completely agree that comments should never explain what the code does, only why. But, it is definitely good practice to put necessary comments into the code. When I go back and look over some of my code (PHP or other), I wish I had commented more clearly.
But, the only standard with comments is consistency! Be consistent and you don't have to worry so much about confusing comments (only about when to use them).
Some (if not most) PHP programmers use the double-slash method (//) for commenting their code. There really is no standard, and I've seen people who comment using the pound symbol (#) at the beginning of a line, and others who comment out blocks with /* and */.
Comments are liars!
The problem with comments is that you have to update them as you update your code. If you don't, you end up with code looking like this:
// sum $a and $b
$x = $a * $a - $b;
So the best way to document your code is to make it really clear! I would write your code like this:
if ( isPositive(3) ) {
doA();
} else {
doB();
}
if( $result ) {
displayConfirmationMsg();
} else {
displayErrors();
}
This code doesn't need comments at all, because it's very simple to understand it!
Well, anyway, when I do have to write comments (almost never), I go with the // notation, but I think it doesn't really matter.
By the way, check out this awesome video of Uncle Bob.
It's been a long running issue that I've come across in many-a-hot-and-steamy coding sessions.
One person codes this way another codes that way. So after much push and pull I'm curious...
Is there any correct way of phrasing a PHP 'IF ELSE' statement?
Personally I use the:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
After many arguments though I've been presented with other options such as:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
}
else
{
$variable = executedifferentfunctiononvariable($variable);
}
OR
if ($variable == 'setvalue')
$variable = executefunctiononvariable($variable);
else
$variable = executedifferentfunctiononvariable($variable);
OR
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
I personally format my if/else like the last one:
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
Your version is kind a mixture of 1 and 3, in my mind.
I have also worked with coders that do all of them and have never heard of a standard one.
The php website uses the last one: http://ca2.php.net/manual/en/control-structures.elseif.php
I also use the second example in some cases when the if statement will always be very short. If there's ever a possibiltiy of it getting longer (more than 1 line each) I'll do #1. I try to avoid #2 when possible cause it's hard to add the {} later.
I use the last one:
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
That being said, it is pretty unimportant which one you go with, just make sure you are consistent.
The Right Way is to follow your project's coding standard. If you don't have one, adopt one from PHP-FIG, Zend, Symfony, etc.
This form appears very popular:
if (condition) {
statements
} else {
statements
}
For variable assignment I'll use a ternary only if the statement can fit legibly on one line:
$variable = !empty($foo) ? $foo : 'default';
Update: I've removed the bit about a multi-line ternary statements as I no longer consider this a wise practice.
I personnally prefer:
if(something){
doSomething();
}
elseif(somethingElse){
doSomethingElse();
}
else{
doAnotherThing();
}
Don't forget about
if (expression):
// code goes here
elseif (another expression):
// code goes here
else:
// code goes here
endif;
I personally like this structure when I'm cooking some tag soup.
The most important thing is that the programmers working on a project pretty much adhere to the same coding guidelines. So have a meeting and pick one or the other, and then stick with it.
I used to do (2) all the time but got it beaten out of me from Java programming as Sun's coding conventions use (4). So now I'm pretty used to (4). I've been doing a bit of C# lately and it seems to use (2) by default (sigh, here we go again).
In PHP from habit I do (4) but (2) is fine too. I don't like (1) at all.
And (3) is dangerous. Personally I think braces should be required by the syntax of the langauge even if its just for one statement. Saves you getting into trouble. I think that's how Perl does it from memory.
What I also hate is when people do this:
if (something) {
// do something
}
else if (something else) {
}
That one drives me batty. So I only find (2) and (4) acceptable. I don't care which one it is, as long as it's done consistently, preferably within the conventions for the language.
There is no right or wrong way, it is an opinion. Personally, I like the last one best (1TBS???). I never use the one without braces, I consider it bad style in general.
The only people that can really answer this question for you are the other people that are going to work on the code. It is important that everone agrees to a coding standard. Which standard you choose is less important than the fact that everyone uses it.
The PEAR coding standard is the PHP coding standard. I would recommend to get used to it as you will find it in other projects such as Zend, Doctrine, Symfony, Horde and many, many more.
http://framework.zend.com/manual/en/coding-standard.coding-style.html#coding-standard.coding-style.control-statements.if-else-elseif
In short, the is no correct way of doing. As long as it works, whatever you feel is the best, you can use. You should pick one and then stick to it, it will make your code easier to recognise.
The only thing is, if you don't include the "{" character you are limited to one expression or function.
Also, if you are only looking to define variables you can use the following code:
$variable = (CONDITIONAL STATEMENT) ? "It was true" : "It was false";
At my company we use:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
}
else
{
$variable = executedifferentfunctiononvariable($variable);
}
I doesn't really matter aslong as there is a standard
Really to me... it just doesn't matter. I believe you should be able to read either way without issues. Does it really matter if the curly brace is on a new line or not? Does it really matter if there's a space after the closing parenthesis or not?
As long as the code is done in a such way that there's been at least an attempt at making it readable, I really just don't care.
Is there a correct way? Well if there was, then why do we have options of doing it differently?
I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?
I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "GOTO 10"-like command...
They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of switch nested if statements. Here's the concept example I found:
<?php
for ($i = 0; $i < 9; $i++) {
if (true) {
break blah;
}
echo "not shown";
blah:
echo "iteration $i\n";
}
?>
Of course, once the GOTO "rumor" was out, there was nothing to stop some evil guys to propagate an additional COMEFROM joke. Be on your toes.
See also:
http://www.php.net/~derick/meeting-notes.html#adding-goto
I'm always astonished at how incredibly dumb the PHP designers are.
If the purpose of using GOTOs is to make breaking out of multiply nested
loops more efficient there's a better way: labelled code blocks
and break statements that can reference labels:
a: for (...) {
b: for (...) {
c: for (...) {
...
break a;
}
}
}
Now is is clear which loop/block to exit, and the exit is structured;
you can't get spaghetti code with this like you can with real gotos.
This is an old, old, old idea. Designing good control flow management
structures has been solved since the 70s, and the literature on all this
is long since written up. The Bohm-Jacopini theorem showed that
you could code anything with function call, if-then-else, and while loops.
In practice, to break out of deeply nested blocks, Bohm-Jacopini style
coding required extra boolean flags ("set this flag to get out of the loop")
which was clumsy coding wise and inefficient (you don't want such flags
in your inner loop). With if-then-else, various loops (while,for)
and break-to-labelled block, you can code any algorithm without no
loss in efficiency. Why don't people read the literature, instead
of copying what C did? Grrr.
Granted, I am not a PHP programmer, and I don't know what PHP's exact implementation of GOTO will look like, but here is my understanding of GOTO:
GOTO is just a more explicit flow control statement like any other. Let's say you have some nested loops and you only need to find one thing. You can put in a conditional statement (or several) and when conditions are met properly, you can use a GOTO statement to get out of all the loops, (instead of having a 'break' statement at each level of nesting with a conditional statement for each. And yes, I believe the traditional implementation is to have named labels that the GOTO statement can jump to by name. You can do something like this:
for(...) {
for (...) {
for (...) {
// some code
if (x) GOTO outside;
}
}
}
:outside
This is a simpler (and more efficient) implementation than without GOTO statements. The equivalent would be:
for(...) {
for (...) {
for (...) {
// some code
if (x) break;
}
if(x) break;
}
if(x) break;
}
In the second case (which is common practice) there are three conditional statements, which is obviously slower than just having one. So, for optimization/simplification reasons, you might want to use GOTO statements in tightly nested loops.
In the example given by steveth45 you can use a function instead:
function findItem(...) {
for (...) {
for (...) {
for (...) {
if (x) {
return theItem;
}
}
}
}
}
// no need for label now
theItem = findItem(a, b, c);
It looks like it's currently in PHP 5.3, but is not fully documented yet. From what I can tell it shares its goto syntax with C, so it should be easy to pick up and use. Just remember Dijkstra's warning and use it only when necessary.
#steveth45
My rule of thumb is that if you have nested code more than 3 levels deep, you are doing
something wrong.
Then you don't have to worry about using multiple break statements or goto :D
there is a goto in php -> http://php.net/manual/en/control-structures.goto.php, but i wouldn't use it, just write normal code...