12

What rules do my namespace names have to follow?

AndreKR
  • 32,613
  • 18
  • 106
  • 168

2 Answers2

13

Variable names follow the same rules as other labels in PHP. 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]*

http://php.net/manual/en/language.variables.basics.php

"Other labels" here does refer to namespaces among other things like class and function names.

Do note that PHP has no native understanding of encodings and treats such labels as mere byte arrays; most Unicode strings (read: UTF-8) will satisfy the above naïve regex:

// yup, works
namespace 漢字;
class 文字 {}
Community
  • 1
  • 1
  • Noob question: I never used namespaces, but I remember seeing something like `namespace one\two`. Would that fit this rule? – sidyll Dec 07 '16 at 21:53
  • @sidyll The backslash is a separator in hierarchical namespaces. – Barmar Dec 07 '16 at 21:54
  • @sidyll The \ is the namespace separator, my question was about the components separated by the separator. Maybe I should make that clear in the question? – AndreKR Dec 07 '16 at 21:55
  • The namespace StillDreaming1\PurposefulPhp is giving me problems because of the 1... – still_dreaming_1 Sep 06 '17 at 15:03
  • Actually the namespace works fine, but it might be a problem with an autoloading bug in composer. – still_dreaming_1 Sep 06 '17 at 15:18
  • the regex supplied in the [php docs](https://www.php.net/manual/en/language.variables.basics.php) is **^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$** which has a different range. I believe \x7f matches the delete character. – S. Imp Feb 22 '21 at 17:39
3

For those stumbling across this question: the following regex will validate a complete PHP namespace (not allowing a preceding or succeeding backslash).

^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\\]*[a-zA-Z0-9_\x7f-\xff]$

When using PHP's preg_match the regex should be used like this:

preg_match(
  '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\\\\]*[a-zA-Z0-9_\x7f-\xff]$/', 
  'Vendor\Package\Valid'
);
Chris Harrison
  • 5,512
  • 3
  • 28
  • 36
  • I am not so sure if consecutive backslashes are allowed. And I am pretty confident starting a namespace segment with number throws syntax error. Howbout this one: `"/(^$)|(^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*(\\\\[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)*$)/"` Also, \x80 as mentioned here: https://www.php.net/manual/en/language.variables.basics.php – informatik-handwerk.de Jun 29 '21 at 19:36