Capital letters in class name PHP

2019-01-14 21:10发布

I have two classes in my system. One is called file and second is File. On my localhost when i instantiate file i get file object, but my friend running the same script gets object of File like the capital letters were unrecognized and "file" was equal to "File". Is that some configurable thing? We are both running on Windows. I have WampServer, he has XAMPP.

3条回答
该账号已被封号
2楼-- · 2019-01-14 21:41

PHP is case insensitive for the class naming. it means you can normally do $file = new file() even if the class is named File and vice-versa.

Are you by any chance relying on the auto loading of class files ? If this is the case, it is possible that depending on the computer, the interpreter don't always find the same file first. This will explain the problem.

I strongly suggest that you rename your classes. It's always a bad idea to rely on case to differentiate two different things and by convention, class names always start with a capital letter.

If you can't change the class names, I suggest to have a look at php namespaces.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-14 21:52

I guess you are using some kind of lazy loading for class files, may be you are programming in a PHP framework. The secret will lie in your __autoload function. Find it.

Check PHP manual for Autoloading.

The following code:

<?php

class file {
    public $a;
}

class File {
    public $a2;
}

$x = new file();

Gives an error: Cannot redeclare class File so again, the trick might be which file is included.

Behavior of your code displays that one of the classes isn't being loaded (otherwise you'll see class redeclare error). It is probably the auto loader that first loads the file class and then when it finds definition to File it simply assumes that that it has already loaded the class (due to case insensitive behavior of PHP).

查看更多
混吃等死
4楼-- · 2019-01-14 21:59

Classnames in PHP are not case sensitive (that doesn't depend on the operating system)

class myclass {}

$x = new MYclaSS;

var_dump($x);

object(myclass)#1 (0) {
}

so as general advice: You shouldn't start and try to mix something there :)

Code like this should not work:

class ab {}

class AB {}

Fatal error: Cannot redeclare class AB in ... on line x
查看更多
登录 后发表回答