james
james

Reputation: 3573

Is there a limit in PHP to the length of a variable name or function name?

If I wanted to write a really long variable name like:

$this_is_my_variable_that_does_something_in_the_following_function_and_provides_some_information_with_which_the_function_relies_upon_to_do_all_the_work_it_needs = null;

would that work? same question for function/method names

Upvotes: 52

Views: 26669

Answers (6)

Rupesh Ranjan
Rupesh Ranjan

Reputation: 7

PHP doesn't have any restriction for variable name. And my suggestion is that variable name must consist the definition of the data which you are gonna store into it.

Upvotes: -3

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

From the documentation:

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

The same is the case for function names, as stated here.

Upvotes: 100

Nikola Svitlica
Nikola Svitlica

Reputation: 642

The limit in variable/function/method/class name length does not exist.

Comments above states that that this property should not be exploited. That is true only when it comes to human readable/human maintainable code.

However, this is extremely useful feature of PHP, that is exploited very well in a lot of very popular projects, such as Twig per example, which generates classes, example (a snippet):

class __TwigTemplate_9601167421099bbb502d119e674fed3fb71769eef256903648c9c2b4b6faa436 extends \Twig_Template {

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_0abebc74dd811fd7b4cfa4c6a2fdf870d7723c04e8daf6926b04914d6644935f = $this->env->getExtension("native_profiler");    
    }

}

I had opportunity to benefit from same property as well in my projects.

In conclusion:

  • There is no limit in var/func/class name length
  • It is extremely useful language feature
  • There is a context for its usage, of course, it is not for every day work

Upvotes: 18

Craige
Craige

Reputation: 2891

PHP does not pose a length limit on it's identifiers.

That said, I'm not sure why anybody would ever want to create a 160 character variable name. I hope this is a hypothetical question.

Upvotes: 3

ceejayoz
ceejayoz

Reputation: 179994

Generally, such a limit is imposed by the threat of violence from other folks who interact with your code.

Upvotes: 251

zsalzbank
zsalzbank

Reputation: 9857

There is no limit - but it is highly not suggested as it creates unreadable code...

Upvotes: 3

Related Questions