Spaces in PHP variable names

Submitted by Frederic Marand on

I just found out a very strange PHP feature by browsing the PHP-GTK2 API with the Reflection classes : spaces can be used in some alien places, like variable names.

But the doc says you can't !

Well, try this in PHP 5.2.5, for instance:

Spaces in PHP variable names

<?php
// Store
${'some var'} = 42;

// Use
echo ${'some var'}; // 42

// List
$arVars = get_defined_vars();
print_r($arVars); // yes, it is there !
?>

Spaces in PHP constant names

The case with constants is better known, being mentioned on php.net :

<?php
// Store
define('SOME CONST', 42);

// Use
echo constant('SOME CONST'); //
// http://www.php.net/manual/en/language.constants.php#76542

// List
$arConst = get_defined_constants();
print_r($arConst); // yes, it is there !
?>

Spaces in other PHP names

Stranger is the fact that you are not allowed to use that same syntax on parameter names, class constants, or class properties: in every case, the syntax fails.

Spaces in PHP-GTK names

So how does this related to PHP-GTK2 ? Actually, I discovered this possibility about spaces in variable names because the Reflection API shows GdkColorMap::alloc_color() like this:

Method [ <internal> public method alloc_color ] {

  - Parameters [3] {
    Parameter #0 [ <optional> $color OR red ]
    Parameter #1 [ <optional> $blue ]
    Parameter #2 [ <optional> $green ]
  }
}

There's a bit of magic in ext/gtk+/gdk.overrides regarding these parameters (starting line 312 in version 1.81), because this is not the default Gdk format.

However, at any rate, it seems that this syntax is not allowable from PHP source, even though the PHP-GTK extension uses it.

I understand what you say, but the doc makes no such detail:
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
It is still rather inconsistent, too: why allow it only on variables and not on class names or parameter names, then ? Although they belong in different spaces, these are still symbols in the same language.

Seth Caldwell (not verified)

Sat, 2012-02-11 00:22

In reply to by Frederic Marand

The reason why its allowed on variables is because of the way object parameters and array keys intermingle - Imagine having an array

<?php
$a
= array('some name'=>'value1','some name2'=>$someotherobject);
?>

and then doing

<?php
$o
= (object) $a;
?>

You will then have to use $o->{'some name'} to get at that value.

You can also then access the other object like $o->{'some name2'}->someotherobjectparameter;