__construct() vs SameAsClassName() for constructor in PHP

后端 未结 11 2737
南笙
南笙 2020-11-28 09:55

Is there any advantage to using __construct() instead of the class\'s name for a constructor in PHP?

Example (__construct):



        
11条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 10:06

    Well it has been a few years since this question was asked, but I think I have to answer this one still, because things has changed and for readers in the future I want to keep the information up to date!


    So in php-7 they will remove the option to create the constructor as a function with the same name as the class. If you still do it you will get a E_DEPRECATED.

    You can read more about this proposal (the proposal is accepted) here: https://wiki.php.net/rfc/remove_php4_constructors

    And a quote from there:

    PHP 7 will emit E_DEPRECATED whenever a PHP 4 constructor is defined. When the method name matches the class name, the class is not in a namespace, and a PHP 5 constructor (__construct) is not present then an E_DEPRECATED will be emitted. PHP 8 will stop emitting E_DEPRECATED and the methods will not be recognized as constructors.

    Also you won't get a E_STRICT in php-7 if you define a method with the same name as the class AND a __construct().

    You can see this also here:

    PHP 7 will also stop emitting E_STRICT when a method with the same name as the class is present as well as __construct.


    So I would recommend you to use __construct(), since you will have less issues with this in the future.

提交回复
热议问题