Positional comparison in php - php

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 :)

Related

PHP Style Guide Conformance

For a new project I've just started, I thought it might be a good idea to adhere to a styleguide for my code. I had sort of settled on a style for myself, but could use a little more structure, since there were a few things that varied between my projects and even sometimes within projects.
Now I've settled on this styleguide: http://www.php-fig.org/psr/psr-2/
Question is though, it says to limit lines of code to 80 characters, so I set up a ruler at that limit in ST3. I'm just not sure what a good practice is in regard to splitting code over multiple lines. How would you split the code below (it's already indented by 8 spaces)?
$this->errorMessage = (isset($this->errorDefinitions[$errorNo])) ? $this->errorDefinitions[$errorNo] : $errorMessage;
Or would it be better to conform to the guide by abandoning the shorthand expression and just writing:
if (isset($this->errorDefinitions[$errorNo])) {
$this->errorMessage = $this->errorDefinitions[$errorNo];
} else {
$this->errorMessage = $errorMessage;
}
There's nothing in the styleguide on this subject. Can anyone point me in the right direction or just tell me where I can find more information on the 'proper' way of doing it. I realize there might not be consensus on the way to do it, but I'd like to read your opinions.
You could break up your shorthand across lines:
$this->errorMessage = isset($this->errorDefinitions[$errorNo])
? $this->errorDefinitions[$errorNo]
: $errorMessage;
Just keep in mind that shorthand ternary statements are awesome... when they are short and simple! But once your conditions become longer you are just making your code harder to read, understand, and ultimately maintain. That's why PSR-2 has the line limit (in part).
Your code is a bit in the fuzzy area from my perspective. Breaking it up like above is ok, but if it was any more complicated at all (called a function, etc) I'd say abandon the shorthand and go with the if.
Ultimately it's your call, as you pointed out PSR-2 doesn't land on this issue.

PHP - Faster to use code

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.

Zend comparison operation style

This may not be an important issue but it bugs me anytime(quite often) I come across it, so I need to put my mind to rest. Please bear with me.
I am more used to seeing and using comparison operations like this:
if($some_var ==NULL){}
But Zend documentation(and only in zend do I notice this) always reverses the operands:
if(NULL ==$some_var){}
I'm not a computer scientist, so I would like to know if the order of these operands matter. Is there a difference or reason why zend documentation chooses the reverse style?
The result is the same. The advantage of this approach is what happens if the programmer accidentally types one equals instead of two:
if ($some_var = NULL) // this will perform an assignment instead of a comparison
if (NULL = $some_var) // this will give you a parse error
so it helps prevent those kinds of coding mistakes.
I prefer to use the Zend style for one reason. If you accidentally type = instead of == or === you will get an error. In the variable-first format, you will silently assign that value to your variable.

Should PHP code have spaces before operators?

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.

What are some useful PHP Idioms?

I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.
Some examples:
Class naming convention to handle namespaces: Part1_Part2_ClassName maps to file Part1/Part2/ClassName.php
if ( count($arrayName) ) // handles $arrayName being unset or empty
Variable function names, e.g. $func = 'foo'; $func($bar); // calls foo($bar);
Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...
Apply liberally for fun and profit:
Iterators in foreach loops. There's almost never a wrong time.
Design around class autoloading. Use spl_autoload_register(), not __autoload(). For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.
Typehint everywhere. Use assertions for scalars.
function f(SomeClass $x, array $y, $z) {
assert(is_bool($z))
}
Output something other than HTML.
header('Content-type: text/xml'); // or text/css, application/pdf, or...
Learn to use exceptions. Write an error handler that converts errors into exceptions.
Replace your define() global constants with class constants.
Replace your Unix timestamps with a proper Date class.
In long functions, unset() variables when you're done with them.
Use with guilty pleasure:
Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.
Use output buffers for assembling long strings.
ob_start();
echo "whatever\n";
debug_print_backtrace();
$s = ob_get_clean();
Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:
Magic methods (__get, __set, __call)
extract()
Structured arrays -- use an object
My experience with PHP has taught me a few things. To name a few:
Always output errors. These are the first two lines of my typical project (in development mode):
ini_set('display_errors', '1');
error_reporting(E_ALL);
Never use automagic. Stuff like autoLoad may bite you in the future.
Always require dependent classes using require_once. That way you can be sure you'll have your dependencies straight.
Use if(isset($array[$key])) instead of if($array[$key]). The second will raise a warning if the key isn't defined.
When defining variables (even with for cycles) give them verbose names ($listIndex instead of $j)
Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.
Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using Zend Framework's naming conventions because they feel right to me.
Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the full backtrace.
Fortunately, namespaces are in 5.3 and 6. I would highly recommend against using the Path_To_ClassName idiom. It makes messy code, and you can never change your library structure... ever.
The SPL's autoload is great. If you're organized, it can save you the typical 20-line block of includes and requires at the top of every file. You can also change things around in your code library, and as long as PHP can include from those directories, nothing breaks.
Make liberal use of === over ==. For instance:
if (array_search('needle',$array) == false) {
// it's not there, i think...
}
will give a false negative if 'needle' is at key zero. Instead:
if (array_search('needle',$array) === false) {
// it's not there!
}
will always be accurate.
See this question: Hidden Features of PHP. It has a lot of really useful PHP tips, the best of which have bubbled up to the top of the list.
There are a few things I do in PHP that tend to be PHP-specific.
Assemble strings with an array.
A lot of string manipulation is expensive in PHP, so I tend to write algorithms that reduce the discrete number of string manipulations I do. The classic example is building a string with a loop. Start with an array(), instead, and do array concatenation in the loop. Then implode() it at the end. (This also neatly solves the trailing-comma problem.)
Array constants are nifty for implementing named parameters to functions.
Enable NOTICE, and if you realy want to STRICT error reporting. It prevents a lot of errors and code smell: ini_set('display_errors', 1); error_reporting(E_ALL && $_STRICT);
Stay away from global variables
Keep as many functions as possible short. It reads easier, and is easy to maintain. Some people say that you should be able to see the whole function on your screen, or, at least, that the beginning and end curly brackets of loops and structures in the function should both be on your screen
Don't trust user input!
I've been developing with PHP (and MySQL) for the last 5 years. Most recently I started using a framework (Zend) with a solid javascript library (Dojo) and it's changed the way I work forever (in a good way, I think).
The thing that made me think of this was your first bullet: Zend framework does exactly this as it's standard way of accessing 'controllers' and 'actions'.
In terms of encapsulating and abstracting issues with different databases, Zend_Db this very well. Dojo does an excellent job of ironing out javascript inconsistencies between different browsers.
Overall, it's worth getting into good OOP techniques and using (and READING ABOUT!) frameworks has been a very hands-on way of getting to understand OOP issues.
For some standalone tools worth using, see also:
Smarty (template engine)
ADODB (database access abstraction)
Declare variables before using them!
Get to know the different types and the === operator, it's essential for some functions like strpos() and you'll start to use return false yourself.

Categories