PHP - Does a class need to have the same name as the file?

There is no link between the file name and the class name, you can name the classes in a file anything you want, have multiple classes or have no classes at all. However, it is a good idea to develop a consistent convention to indicate what the file contains via its file name.

Edit:

See Jason McCreary's answer below as some of these conventions have changed.


No on both accounts. These are simply common conventions of PHP developers. It's up to you if you wish to follow them.

Update

While my original answer is still technically correct, the conventions have changed in the last 5 years. Notably the PHP Standards Recommendations released PSR-0 and now PSR-4. These outline file names of PHP classes as well as their path and how they should be namespaced and autoloaded.

You should read the spec for more details, but to paraphrase, the filename should match the class name with a .php extension and the path should match the class namespace.

For example, the class Widget with namespace Acme, would have the path: base/path/Acme/Widget.php.

Tags:

Php

Oop

Class