Is it right to create 2 classes in one php file ?.

  • one
    It depends on what classes. If classes are somehow logically related, then why not? - Anton Shchyrov
  • In 98% of cases they will tell you that the location in one file is bad practice ..... However, it all depends, you know , Alexey Shimansky

2 answers 2

No, not right, but PHP allows you to do this, as well as placing classes in different namespaces inside a single file.

Consider this a bad practice.

  • one
    And if it is an internal class? How in java nested (nested and inner)? why not? - Alexey Shimansky
  • Read PSR-1: Namespaces and classes MUST follow an “autoloading” PSR: [PSR-0, PSR-4]. The namespace is at least one level: a top-level vendor name. Therefore, if you want to write "good code", then this behavior is not recommended. - Zhukov Roman
  • And why do I need autoload for the inner class?) It is created at the expense of the parent - Alexey Shimansky
  • one
    I know what a PSR is, thank you) However, this does not in any way negate the fact that inner classes that are used in outer will in no way fall into autoload and, if they relate only to them, can be located inside - Alexey Shimansky
  • one
    And where did I say that they could not? My question was about "right" and "wrong." Java has its own concepts of correctness, PHP has its own. - Zhukov Roman

No, wrong, because autoload.

Well, that is theoretically possible, but in practice, the autoload will look for a class to load in the file that matches the class name.

  • You can use the second class if it is not needed in autoload, for example, when it is used only in the first class. But in practice, except for inflating the file, it does not give anything. - Zhukov Roman