PHP reserved words as namespaces and class names

后端 未结 1 615
孤街浪徒
孤街浪徒 2020-12-11 20:12

Recently I\'ve started converting my framework to use the php namespaces and one question to which I can\'t seem to find the answer is - is it \'legal\' to use reserved word

相关标签:
1条回答
  • 2020-12-11 20:16

    PHP will throw an error like:

    Parse error: syntax error, unexpected T_ARRAY, expecting T_STRING
    

    if you try:

    class Array
    {
    
    }
    $myClass = new Array;
    

    Instead, try something like

    class myArray
    {
    
    }
    $myClass = new myArray;
    

    [edit] I'll elaborate on that a little, they're reserved for a reason because in the first scenario above, PHP wouldn't be able to tell the difference between you defining an array or initialising a class of the same name, so it throws an error. There's no way round this like in MySQL, for example, where you can escape reserved words with a backtick. So in PHP you're forced to change the name, you don't have to change it much, one char will do as long as you're not using the exact same name as a reserved word.

    Hope that helps!

    0 讨论(0)
提交回复
热议问题