PHP and the Gem Within

23 11 2017

Flickr: by Hetx

Ubiquitous and lithe, little characters, popping up anywhere from user-defined functions to control structures and class definitions, PHP’s curly braces depending on circumstances may exhibit a distinctly Perlish quality. Perl exerts an influence since it figures as one among three languages from which PHP, indelicately-speaking, purloins much of its syntax. PHP’s connection to Perl also relates to its predecessor PHP/FI, originally a Perl hack that Rasmus Lerdorf later rewrote in the C Programming Language. To better appreciate PHP, certainly its Perlish facet merits inspection, and complex (curly) syntax, lends itself well to this endeavor.



Curly Goodness

The default syntax for representing variables in Perl and PHP entails prepending a bareword, i.e. an unquoted string with a sigil. If you need to create a variable name from a complex expression one needs to resort to coding with the complex syntax. PHP inherits this coding style from Perl. The following example demonstrates the technique in Perl:

$f = 'flower';
$b = 'bed';
${$f . $b} = 'English lavender';
print("The fragrant ${$f . $b}...");
See live code.

According to Sams Teach Yourself Perl in 21 Days:

The curly braces in this case are simply delimiters so that Perl can figure out where the variable name starts and ends…

Note the preceding Perl snippet, virtually indistinguishable from PHP which follows:

<?php
$f = 'flower';
$b = 'bed';
${$f . $b} = 'English lavender';
print("The fragrant ${$f . $b}...");

See live code.

Despite the connotation of the nomenclature “complex syntax”, the only complex aspect involves endowing the coder with the ability to create complex expressions; the syntax itself requires simply the addition of a pair of curly braces. Appearing first in PHP 4 per the Manual, the syntax provides a developer with a handy convenience to code a variable by utilizing a string or expression.

Property à la Pretty

The foundational work, Programming Perl by Larry Wall et al, instructs as follows:

… if you want an object called $city to have a data field named elevation, you can simply access $city->{elevation}

The following Perl snippet illustrates how to both set and read an object’s data field or, using PHP parlance, property:

$city->{elevation} = "500 ft";
print($city->{elevation});
See live code

Translating this example into PHP requires scant effort:

$city = new stdClass;
$city->{"elevation"} = "500 ft";
print($city->{"elevation"});

See live code

Unlike Perl, PHP mandates that one must explicitly instantiate an object in order to assign it a property. Also, one must always quote the property of a PHP object when using the complex syntax, even if one embeds the object in a double quoted string.

Routine Complexity

Perl permits the arrow operator and curly braces to encapsulate a subroutine instead of a string. When the subroutine executes and returns a string, that value becomes the name of a variable; see chapter 8 of the aforementioned canonical tome.

The following demonstrates the technique:


$o->{"rose"} = "red";
$o->{"violet"} = "blue";
#
# displays "red" or "blue"
print( $o->{Test()} );
#
# Test() returns either "rose" or "violet"
# depending on time of day
sub Test(){
$t = time();
return( ($t % 2) == 1)? "rose" : "violet";
}
See live code.

The subroutine behaves more like a function in this example, returning a flower type based on the parity of time. That value then becomes associated with an object’s property which allows the print function to display its value.

Since PHP 5.5, developers have been able to code similarly, as follows:

<?php
function Test(){
  $t = time();
  return ($t % 2 == 1)? "rose" : "violet";
 }
$rose = "red";
$violet = "blue";

$clr = "${Test()}";
echo "\n",$clr;

See live code.

In earlier versions of PHP, the code works as long as you prefix the function with an “@” symbol to suppress displaying an error message; see bug report #61681.

Embraceable Variable Interpolation

Curly braces facilitate variable interpolation in a double-quoted string, as the next example demonstrates.

<?php
$foo = new stdClass;
$foo->bar = new stdClass;
$foo->bar->baz = "test";
echo "{$foo->bar->baz}";

See live code. Issue raised in this early bug report.

PHP expands on the usefulness of the “{}” characters so that they may encompass an entire expression, and aid with extracting the value contained in this snippet’s hierarchy of objects.

You may even use two sets of curly braces if necessary as the following example depicts:

<?php
$object = new stdClass;
$object->clr = "blue";

echo "Lovely Texas {$object->{'clr'}}bonnets";

See live code.

The inner curly braces delimits the start and end of a string while the outer set delimits the object and its $clr property. Without the outer braces, the code raises this error in PHP 7:

Object of class stdClass could not be converted to string…

Perl performs most efficiently in this respect without any necessity of adding the outer curly braces, as this snippet indicates

$object->{'clr'} = "blue";
print("Lovely Texas $object->{'clr'}bonnets");
See live code.

Rule Breaker

Another benefit of complex syntax involves offering a way to deviate from the rules concerning identifiers for variables and object properties. In PHP the names for these entities should comprise strings whose initial character starts with a letter. But, with complex syntax, one may gleefully subvert the rules. This ability, too, stems from Perl which offers a convenient way to write the most unlikely code. Consider the following:

${" "} = "blank space";
print(${" "});
See live code.

PHP, taking its cue from Perl, obediently supports writing such stunning code, as you may note in this next example:

<?php
${" "} = "blank space";
var_dump(${" "}); // blank space
$a = get_defined_vars();
echo array_key_exists(" ",$a)? "Yes" : "No","\n";
echo isset(${" "})? 'true': 'false';

See live code

One may write similar code in PHP for object properties, as follows:

<?php 
$obj = (object) [' ' => 456];
$obj->{' '} = "blank space");

See livecode

After the array is cast as an object, the result is a stdClass object assigned to $obj. Ordinarily, the object’s property would be accessed using the arrow operator, but in this case the property bears a non-lettered name which creates an issue, mercifully resolved with the complex syntax.

The Fly in the Ointment

In some cases, you may wish to have curly braces visible in double quotes along with the variable’s value. When this issue cropped up in PHP 4 (see here), the suggested fix involved escaping each curly brace with a backslash, unfortunately, a solution no longer. Instead you may code as follows:

<?php
$timeOfDay = "morning";
// not quite right
echo "Good \{$timeOfDay\}!\n";
//feasible:
echo "Good {", $timeOfDay, "}!\n";
echo 'Good {' . $timeOfDay . '}!';
// best:
echo "\nTop of the {{$timeOfDay}}!";

See live code here.

Recommended Reading

This work is licensed under a Creative Commons License

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: