Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use PHP reserved names for my functions and classes?

I'd like to create a function called "new" and a class called "case".

Can I do that in PHP?

like image 537
Ciprian Mocanu Avatar asked Mar 14 '11 12:03

Ciprian Mocanu


People also ask

Can you use keywords for variable names in PHP?

What is a keyword. In PHP there are certain words that's reserved for a special use. We cannot use these words when naming our variables, constants, arrays, functions, interfaces and classes. These keywords have special meaning and is only to be used in special contexts.

What is the correct way of naming a class in PHP?

A valid class 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]*$ .

Is object a reserved word in PHP?

In PHP 7.2. 0RC2, Object is a reserved word.


2 Answers

No, you can't. Thank god.

like image 151
Lightness Races in Orbit Avatar answered Nov 05 '22 14:11

Lightness Races in Orbit


Actually, while defining such a method results in a parse error, using it does not, which allows some kind of workarounds:

class A {
    function __call($method, $args) {
        if ($method == 'new') {
            // ...
        }
    }
}

$a = new A;
$a->new(); // works!

A related feature request dating back to 2004 is still open.

Edit January 2016

As of PHP 7, it is now possible to name your methods using keywords that were restricted so far, thanks to the Context Sensitive Lexer:

class Foo {
    public function new() {}
    public function list() {}
    public function foreach() {}
}

You still can't, however, name your class Case I'm afraid.

like image 45
BenMorel Avatar answered Nov 05 '22 16:11

BenMorel