Literals

What are Literals and why would we use them?

Literals are pieces of data that are explicitly used. A literal string, for example, might be used for the label for a field. Literals are used when a static (as in unchanging) piece of data is needed. Say we need to calculate something based on days, not weeks. We could use a variable and give it a value of 7. We could also use a literal value of 7 in the calculation.

Use literals when the value is used once for strings. For numeric values (like 7) we might use the literal multiple times. The key with numerics is whether the value of 7 by itself is clear enough to convey its purpose. Using numerics without a clear source for the value is often referred to as “magic numbers”. This is a bad thing. If you use numerics in a manner that is unclear, at the very least, document each value so anyone reading it can determine each number’s purpose.

Some Examples

The following examples are to show good and bad uses of literals.

Good:

$first = substr($name, 0, 1); // we need the first letter of the name as a key

This shows the use of two literals and describes the point of the values.

Bad:

$result = 45.64*($eval+4.643); // compute the result

This shows a bad example where the numbers used have no clear source or purpose. Don’t do this.

Good:

$label = 'Sample values';

This assigns a value to the variable and is fairly clear as to the point of the literal.

Bad:

$label = $p.\'e\'.$w.\'+4\'.$rr;

This needs a comment to indicate what is going on here.

$a = "What we now know";
$b = "What we now know";

Would be far better written as:

$a = "What we now know";
$b = $a;

since we only need to make a change in one place to fix any mistake in the literal.

One Last Thing

In PHP, literals surrounded by " characters are evaluated, but literals surrounded by ' characters are not. Using unevaluated strings can often speed up processing, but it is interesting to note that

$a = "$b/$c";

executes faster than

$a = $b.'/'.$c;