What are the valid characters in PHP variable, method, class, etc names? -


what valid characters can use in php names variables, constants, functions, methods, classes, ...?

the manual has some mentions of regular expression [a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*. when restriction apply , when not?

the [a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]* regex applies when name used directly in special syntactical element. examples:

$varname           // <-- varname needs satisfy regex $foo->propertyname // <-- propertyname needs satisfy regex class classname {} // <-- classname needs satisfy regex                    //     , can't reserved keyword 

note regex applied byte-per-byte, without consideration encoding. that's why allows many weird unicode names.

but regex restricts only these "direct" uses of names. through various dynamic features php provides it's possible use virtually arbitrary names.

in general should make no assumptions characters names in php can contain. parts arbitrary strings. doing things "validating if valid class name" meaningless in php.

in following provide examples of how can create weird names different categories.

variables

variable names can arbitrary strings:

${''} = 'foo'; echo ${''};      // foo ${"\0"} = 'bar'; echo ${"\0"};    // bar 

constants

global constants can arbitrary strings:

define('', 'foo'); echo constant('');   // foo define("\0", 'bar'); echo constant("\0"); // bar 

there no way dynamically define class constants i'm aware of, can not arbitrary. way create weird class constants seems via extension code.

properties

properties can not empty string , can not start nul byte, apart arbitrary:

$obj = new stdclass; $obj->{''} = 'foo';   // fatal error: cannot access empty property $obj->{"\0"} = 'foo'; // fatal error: cannot access property started '\0' $obj->{'*'} = 'foo'; echo $obj->{'*'};     // foo 

methods

method names arbitrary , can handled __call magic:

class test {     public function __call($method, $args) {         echo "called method \"$method\"";     } }  $obj = new test; $obj->{''}();    // called method "" $obj->{"\0"}();  // called method "\0" 

classes

arbitrary class names can created using class_alias exception of empty string:

class test {}  class_alias('test', ''); $classname = ''; $obj = new $classname; // fatal error: class '' not found  class_alias('test', "\0"); $classname = "\0"; $obj = new $classname; // works! 

functions

i'm not aware of way create arbitrary function names userland, there still occasions internal code produces "weird" names:

var_dump(create_function('','')); // string(9) "\0lambda_1" 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -