What is the difference between public and private in the case of the PHP class constructor and on what grounds should an access modifier be chosen for the class constructor?
- oneDo you want to leave the possibility of constructor inheritance - do public, do not want - private - ilyaplot
- @ilyaplot But what about calling the constructor from the outside? - teran
- @teran And no one talks about using a constructor. Can a class be used statically? - ilyaplot
- one@ilyaplot Well, I’m talking about that and saying that the essence is not only in inheritance, but in general the prohibition of access to it and the prohibition of creating instances of a class outside this class itself. - teran
- @teran, That's about banning the creation of class instances outside the class - the most important. - Hokov Gleb
1 answer
An object of a class with a public constructor can be created anywhere in the program through the new classname
A class object with a private constructor can be created only within the methods of this class itself (for example, in a static method)
Therefore, a private constructor is used when you want the objects of this class to be created only in a certain way from one or several static methods of this class and cannot be freely created in external code. For example, it is necessary for the singleton
Regarding the inheritance mentioned in the comments, there is still a protected level. A constructor is possible to inherit, but it is still not possible to create an object of a class from outside the class. And an important point - the heirs can expand the scope of the method and this is not a violation of the class contract and inheritance. Those. a successor class can declare its constructor public, even if the base class constructor was private or protected . Often, this makes a final protected constructor, from which another method is called, which can override the heir - this also preserves the ability to execute some initialization logic and ensure that the class constructor does not become public.
class foo { public static function create() { return new static; } final protected function __construct() { $this->init(); } protected function init() {} } class bar extends foo { protected function init() { var_dump(__METHOD__); } } bar::create(); - Thank you for the quality explanation! - Lateral Gleb