开发者

Which is the best method to perform string concatenation in PHP?

In php we can append strings in many ways.

            Method 1
            ----------------------------
            $sql  = "SELECT field1, ";
            $sql .= "       field2, ";
            $sql .= "       field3, ";
            $sql .= "       field4, ";
            $sql .= "FROM   table1 ";
            $sql .= "WHERE  condition1 = '".$value."' " ;

            Method 2
            ----------------------------
            $sql  = 'SELECT field1, ';
            $sql .= '       field2, ';
            $sql .= '       field3, ';
            $sql .= '       field4, ';
            $sql .= 'FROM   table1 ';
            $sql .= 'WHERE  condition1 = "'.$value.'" ' ;

            Method 3
            ----------------------------
            $sql  = 'SELECT field1,
                           field2,
                           field3,
                           field4,
                    FROM   table1
                    WHERE  condition1 = "'.$value.'" ' ;

        开发者_JAVA百科    Method 4
            ----------------------------
            $str = <<<HEREDOC
                    SELECT field1,
                           field2,
                           field3,
                           field4,
                    FROM   table1
                    WHERE  condition1 = "$value"
            HEREDOC;

Which of the above is the best approach? Are there any other methods which will result in better performance?


I vote for Method 3.

The less concatenation operations, the better.

Also, you should use single quotes as often as possible to avoid the PHP parser having to interpolate variables inside your strings.


As far as I'm concerned there is no 'best method'.
Rule of thumb is choose one you prefer and stick to it and be consistent across the project.


creating the query itself doesn't take the smallest amount of memory or cpu(it does but in such small nr that it doesnt matter) from your computer but running it, is what you should be concerned about, make sure you have a proper index and so on


None is better. Just select one and stick to it, PHP_CodeSniffer can be used to automate a check on your code style.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜