. NET programmers learn PHP: common programming errors

Source: Internet
Author: User
Tags php compiler php exception handling
In this article, I will continue my PHP journey and collect and summarize some common PHP errors found on the internet, hoping to help you. 1. small errors can make a big mistake. Have you ever encountered a major program problem caused by a small semicolon? In PHP, if you add a semicolon after the while LOOP condition

In this article, I will continue my PHP journey and collect and summarize some common PHP errors found on the internet, hoping to help you. 1. small errors can make a big mistake. Have you ever encountered a major program problem caused by a small semicolon? In PHP, if you add a semicolon after the while LOOP condition

This article will continue my PHP journey and find some PHP files on the Internet.CommonOfErrorWe hope to help you with the collection and summary.

1. Small ErrorIt can also make a big disaster

Have you ever encountered a major program problem caused by a small semicolon? In PHP, if you add a semicolon after the while LOOP condition, it will cause PHP to fall into an endless loop.ErrorThe settings are not captured by the PHP exception handling system. Let's first look at the Code:

$i=0;
while($i<20); {
//some code here
$i++;
}
echo$i;

This Code does not cause system reportsErrorHowever, it will cause the system to enter an endless loop and eventually return execution timeout due to the inability to respond in a timely manner.Error.

However, C # will be captured by the compiler at compilation, and the compiler will know that this is an empty loop.Error. Of course, if the user must be stupid enough to write another endless loop compiler, there will be no way, such:

int i =0;
while (i <20) ;

In this case, the compiler will not report an error.

2. I forgot to add a semicolon after break or continue.

It is also a small symbol that causes a huge difference. Let's look at the following code first:

for($i =0; $i <10; $i++) {
for($j =0; $j <10; $j++) {
if($i ==0)
break
print $j;
}
}

This code will only output 0 results and exit the loop. However, our intention is to output other numbers except 0. Of course, if we use the canonicalized method (for example, we increase the brackets after the if condition is determined ),ErrorIt is easy to avoid.

3. Single or double quotation marks?

Strictly speaking, this article cannot be counted.ErrorFirst, let's look at the following two lines of code:

echo ‘it\’s ok’;
echo “it’s not”;

PHP is not like C #. Single quotes and double quotation marks can be used to represent strings. Therefore, many new PHP users often cannot tell when to use the symbols to enclose strings, or simply use the symbols when to use them. However, single quotes and double quotes are skillful in PHP. If a string starts with double quotation marks, only the double quotation marks are parsed by the analyzer. In this way, you can include any other characters in the double quotation marks, or even single quotation marks and PHP variables. E.g.

$ Var1 = 'Sean zhu ';
Echo 'hello, $ var1. I'm Mike! '; // Output: Hello, $ var1. I'm Mike!
Echo "Hello, $ var1. I'm Mike !"; // Output: Hello, Sean Zhu. I'm Mike!

However, the larger the capability, the larger the consumption, and the complicated function of double quotation marks also means that the compiler takes more time to process it. Therefore, if we only want to output a simple string, it is best to use single quotes.

4. Compare floating point numbers

As A. NETProgrammerIf you see the following code, do you know the result?

$a=0.1+0.2;
$b=0.3;
if($a==$b){
echo'a equals b';
}
else{
echo'a dosen\'t equal b';
}
?>

In. NET, we can know without hesitation that it outputs the answer of a = B, but here is the PHP world, so never believe that the floating point result is accurate to the last one, do not compare two floating point numbers for equality.

5. Can we call method_exists () if the returned result is true?

PHP is not like C #. Since C # Is a static language, we can call any method with confidence (as long as the compiler says no problem ), however, in php, everything remains unknown as long as you fail to execute the final method. Therefore, we sometimes need to perform additional checks before calling the method. method_exist () is one of them. However, if the method is protected or private, the method returns true.

6. Use uninitialized Arrays

Let's take a look at the following code?

foreach($itemsas$item) {
$itemIds[] =$item->getId();
}
?>

. NETProgrammerYes, it will never be the same.ErrorBecause the compiler will help us check, but as a PHPProgrammerAlways remember to initialize the Array: $ itemIds = Array (); you may say that the above Code will not be initialized. Yes. Normally, when the element in the $ items array is greater than 1, this code is OK. However, if the $ items object is empty or the number of elements in it is 0, this code will be faulty.

7. include ("pages/". $ _ GET ["pg1"]);

. NETProgrammerAlthough there will also be various injection attacks, at least they will not. In fact, we should check not only the $ _ GET () parameter, but also other values such as $ _ POST and $ _ REQUEST are highly risky. If you always trust users, you may not know how to load others' code without knowing it.

8. Add quotation marks to the array index

Echo $ array [my_key]; // It works normally, but should not be used
Echo $ array ['my _ key']; // Correct Method

The PHP compiler will think that a string without quotation marks is a defined constant, and then it will find this constant in the symbol table, only when it cannot be found, it converts the key value to a real string, which is why the above Code can also work.

9. strpos/ The stripos function is improperly used.

This function also has a similar in. NET: string. IndexOf (), but in. NET we generally do not commit this elementaryErrorLet's take a look at the following code.

if (strpos(‘Spring Brother is cool, isn’t it?’, ‘Spring Brother’)) {
echo “Spring Brother is cool”;
} else {
echo “Spring Brother is NOT cool”;
}

Guess what the output result is? Yes, it will output "Spring Brother is NOT cool", because, just like in. NET, as the index starts from 0, strpos returns 0 to false. In. net, ifProgrammerDo not perform forced conversion.ErrorIt is easy to see.

Solve this problemErrorYou can use either of the following methods:

If (strpos ('spring Brother is cool, isn' t it? ', 'Spring Brother )! = False ){
// Or
If (strpos ('spring Brother is cool, isn' t it? ', 'Spring Brother')> = 0 ){

10. Use = to compare the data type.

ThisErrorIn fact, it is the same as in js. Because PHP and js are both weak languages, sometimes we may encounter unexpected things when comparing two objects. See the following code:

$a=1;
$b= ‘1′;
$c=1;
$a==$b// true
$a===$b// false
$a===$c// true

We can see that even if $ a and $ B are not the same object, the result of = comparing returns is true, therefore, we recommend that you use = and! = Comparison character.

11. The empty () method and the magic method _ get are used together.

The magic method is very useful, but when it is used with the empty method, we need to be very careful, first go to the Code:

Code

Class Example {
Publicfunction _ get ($ name ){
Return 'this shoshould not show up as empty ';
}
}
Function t7 (){
$ E = new Example ();
If (empty ($ e-> something ))
Echo 'something condition is true ';

$ Var = $ e-> something;
If (empty ($ var ))
Echo '$ var condition true ';
}
T7 ();

We will find that the first condition is true, but the same value is false in the second condition.

12. No protection for sensitive data in the Session

OneCommonPHP securityErrorThat is, no encryption is performed on the sensitive data stored in the Session. To some extent, this is equivalent to exposing the user's password and other information to the network. Some hackers can steal the user's password information through Sesion forgery and other technologies.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.