This question is sort of sub-question of my other question. I figured I'd break off this simple one because the other question is perhaps TLDR and is not getting any engagement.
What are the character requirements for namespaces and subnamespaces? I did some cursory experimentation and noticed that periods and dashes are not permitted in namespaces (at least not in php 7.4) but then I wasn't sure if you might be able to use these characters if you express your namespace dynamically (e.g., in a string variable or as an expression). The docs on namespaces don't seem to offer much guidance. The docs on php basics, however, do offer a regex:
^[a-zA-Z\x80-\xff][a-zA-Z0-9\x80-\xff]*$
If I explode()
a namespace expression on the \
chars, will this regex correctly winnow out the valid ones versus the invalid ones? Some interesting results:
$chk = [
"Foo",
"F1",
"1",
"1F",
"F-1",
"F.1",
"Φ",
"😊",
"/",
"#",
"Foo\Bar",
"\\",
""
];
foreach($chk as $c) {
if (preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $c)) {
echo "MATCH: " . $c . "\n";
} else {
echo "NOPE: " . $c . "\n";
}
}
The results:
MATCH: Foo
MATCH: F1
NOPE: 1
NOPE: 1F
NOPE: F-1
NOPE: F.1
MATCH: Φ
MATCH: 😊
NOPE: /
NOPE: #
NOPE: Foo\Bar
NOPE: \
NOPE:
And YES you can use a smiley face emoji as a variable name or class name. This code works just fine:
$😊 = "smile!";
echo $😊 . "\n";
Is this a good function to check a potential namespace segment to make sure it's valid?
function isValidSegment($segment) {
return (boolean)preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $segment);
}
or would it return false positives or false negatives?