Copy the code The code is as follows:
/* PHP code */
header("Content-type: text/javascript");
if (!haveCookie('cookieName')) {
// ... do something
?>
/* Javascript code */
if ('undefined' == typeof document.cookie['cookieName']) {
setCookie('cookieName', 3600);
}
// ... do something with Javascript
}
?>
At first glance, the code seems to be flawless, but our dear Xiao Ma still discovered the problem. That judgment in Javascript is always true
Copy the code The code is as follows:
if ('undefined' == typeof document.cookie['cookieName']) {
// ...
}
Because this code has a premise on the PHP side, that is, it will be displayed on the client when
if (!haveCookie('cookieName')). Then, when this condition is not met, this code will naturally not be thrown to the client. It seems a bit general to say this, so let’s put aside the Javascript code first, let’s simply use the PHP code to describe it
Copy the code The code is as follows:
header("Content-type: text/javascript" );
if (!haveCookie('cookieName')) {
if (!haveCookie('cookieName')) {
setCookie('cookieName');
}
}
?>
This makes it clear There are many, and it is easy to find the problem - we inadvertently make one more judgment, although this is executed by Javascript on the client side.
To summarize, here are some of the nonsense I thought of from this code:
The longer the code, the higher the efficiency is not necessarily higher
Without affecting the logic and process, try to write multiple judgments together
Try to keep the complexity as low as possible Functions are judged beforehand
Too many judgments can easily lead to reduced program efficiency. Pay special attention when using functions with high time complexity in judgment
If you find that if is nested too much, you have to reconsider the process and algorithm
Robust Code is not guaranteed by excessive judgment
After simplifying the code, many undiscovered problems will be discovered
Excessive judgment, understood from another angle, is a lack of confidence in the code
Finally, thank you again Comrade Xiao Ma.
The above introduces some issues that come to mind from php if, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.