Starting Out in PHP

James DeFillippo (see his bio in Contributors)

Problem

I’m new to PHP and want some general tips on optimizing my application so that it can scale gracefully.

Solution

One of the easiest and most overlooked ways to optimize a PHP application is the proper use of double and single quotes when handling strings. Using double quotes only where they are entirely necessary can give your app the runway it needs to get off the ground.

For example, you wouldn’t want to use:

echo "This is a simple piece of text with a single $variable";

when this is faster to execute with much lower memory requirements:

echo 'This is a simple piece of text with a single ' . $variable;

Discussion

When dealing with strings in PHP, there are two ways of using quotation marks to wrap your strings. One involves using single quotes (') and the other uses double quotes ("). There is a major difference—not only in functionality, but also in speed—when it comes to using the two different options.

PHP will take anything wrapped in a matching set of single quotes and treat that as a string literal. Literally anything in between single quotes is a string and should be treated as such, with no interference from the parser. If you wrap the string in double quotes, though, PHP will parse every element in that string looking for variables for reassignment. Even if none are present, it still has to look, which means if you are wrapping any piece of text in double quotes that does not have a variable in it, you’re ...

Get Facebook Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.