11
Generally, when we define names for class and functions, there is a concern when colliding with the palavras-chaves
of language.
The curious thing is that I noticed that in PHP it is allowed to define class and functions with the same name as certain keywords.
Definitions that do not cause errors
For the following examples below, the definition does NOT generate errors.
class Int{}
class Object{}
class String{}
Including in the Cakephp
there is a class called Object
. And, in the ZendFramework
, exists Zend\Form\Annotation\Object
.
And we still have the functions. Note that it comes to seem contradictory to the statement below:
function int($int)
{
return (int) $int;
}
var_dump(int('1')); // int(1)
Definitions that generate error
In the examples below, I used two keywords. A very common one, which is array
, and another is the one that was added in the version 5.4
of PHP, which is callable
.
class Callable{}
class Array{}
And we have the following result:
syntax error, Unexpected 'Callable' (T_CALLABLE), expecting Identifier (T_STRING)
syntax error, Unexpected 'Array' (T_ARRAY), expecting Identifier (T_STRING)
The questions
I must worry about not declare classes and functions with the name of these keywords described above (whether accepted in the declaration or not)?
Or there is no problem in doing so, since the famous frameworks above use this practice?
Is there any recommendation when names can be used or not used, when it is a name of a
palavra-chave
? For when will I know that I "am released" to declare a class with such a specific name.
Note
I just wanted to record a problem that occurred for those using framework versions Laravel 3
. In it there was a function called yield
. The Laravel 3
was developed for the PHP 5.3
. But later, the PHP 5.5
"invented" the reserved word yield
, that caused the Laravel 3
did not work in PHP 5.5, as it generated a E_PARSE
. And so developer would have to get stuck between version 5.3 and 5.4 of PHP if they kept the Laravel 3
.
What if language allows some reserved words to be used in methods and leaves you more comfortable to develop your classes the way you want? https://wiki.php.net/rfc/context_sensitive_lexer
– gmsantos