Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable / function / class names using special characters

I understand that the underscore _ is an acceptable character for naming variables / functions / classes etc. However I was wondering if there are any other special characters which can be used. I tested out a few with no luck and have assumed for a long time that there are not, however I figured I would see if anyone else knows for certain. This would be mostly for aesthetic purposes, however I imagine a special character naming convention would be useful when working with other developers to define value types etc.

like image 957
grep Avatar asked Jun 15 '11 18:06

grep


People also ask

Can special characters be used in variable name?

After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are allowed. Uppercase characters are distinct from lowercase characters.

Which is a valid character for string a PHP function name?

Function names follow the same rules as other labels in PHP. A valid function 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_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$ . See also the Userland Naming Guide.

Why are special characters not allowed as variable names?

Fundamentally it is because they're mostly used as operators or separators, so it would introduce ambiguity.

How do you name a class in PHP?

Class names should be descriptive nouns in PascalCase and as short as possible. Each word in the class name should start with a capital letter, without underscore delimiters. The class name should be prefixed with the name of the “parent set” (e.g. the name of the extension) if no namespaces are used.


1 Answers

If you check the docs on variables it says that:

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]*'

But basically people have agreed to only use a-zA-Z0-9_ and not the "fancy" names since they might break depending in the encoding one uses.

So you can have a variable that is named $aöäüÖÄ but if you save that with the wrong encoding you might run into trouble.


The same goes for functions too btw.

So

function fooööö($aà) { echo $aà; }

fooööö("hi"); // will just echo 'hi'

will just work out (at least at first).


Also check out:

Exotic names for methods, constants, variables and fields - Bug or Feature?

for some discussion on the subject.

like image 73
edorian Avatar answered Oct 13 '22 21:10

edorian