ES6 supports the Symbol type that is a replacement to hard-coded
identifiers where it are not really need.
I like to suggests a similar feature to PHP.
#0: it should be a partial class that could not be instantiated (new symbol
should be invalid, like an abstract class).
In this point I should suggests two options:
-
It should works like a new keyword "symbol", but that could be extended
like a class when need. (It will make sense on item #2). But could be
referenced directly without need of the ::class. (eg. $a = symbol;). -
Other option is use it as a new keyword "symbol" followed by a \Symbol
reference class (like "instanceof Class" works). Eg. $a = symbol \Symbol;
Anyway, maybe \Symbol could works as a default type, so only $a = symbol
could be do the job. Or even consider symbol as a language constructor,
allowing symbol(\Symbol), for instance.
Ok, now to all make senses (I do expects), keep reading... (I will use
otpion 2 as reference for now)
#1: It could be used to fill constants, for instance, with "magic
identifiers" that have no real value, needly.
Eg.:
public const
USER_NOT_FOUND = symbol(),
USER_INVALID = symbol();
Where USER_NOT_FOUND !=/!== USER_INVALID.
#2: Another possibility is to extends it as an class, so it could be used
as parameter typehint: (not available on ES6, I guess)
class UserErrorSymbol extends \Symbol {}
public const
USER_NOT_FOUND = symbol(UserErrorSymbol),
USER_INVALID = symbol(UserErrorSymbol);
public function setError(UserErrorSymbol $error) {...}
#3: it should have a fallback name (storing a scalar value), so in case you
need to persist it (or serialize), so you could give a name:
public const
USER_NOT_FOUND = symbol(UserErrorSymbol as "UserNotFound"),
USER_INVALID = symbol(UserErrorSymbol as "UserInvalid"),
USER_INVALID_B = symbol(UserErrorSymbol as "UserInvalid");
symbol_alias(USER_INVALID) === 'UserInvalid'
(string) USER_INVALID === 'UserInvalid'
USER_INVALID !=/!== USER_INVALID_B
#4: it could be used as a kind of anonymous array or object key:
$arr[symbol()] = 1;
$arr[symbol()] = 2;
count($arr) === 2
$obj->{symbol()} = 1;
$obj->{symbol()} = 2;
count(get_object_vars($obj)) === 2
But symbol could not be accessed without a valid reference:
echo $arr[symbol()]; // error: index symbol() is undefined or maybe symbol
type could not be used directly to read an array value
$symbol = symbol();
$arr[$symbol] = 1;
echo $arr[$symbol]; // print 1
It is just a draft, but I do belive that it will be a good feature for PHP.