Methods with the same name as their class will not be constructors

If you are using older PHP programs, you might see error messages, either on screen (oops, you should turn those off) or in your error_log file (that’s where error messages belong).

In PHP 7, there are several functions that are now deprecated and won’t run, that have been labeled for years as “will be deprecated”. Programmers should have updated their code long ago.

One of the deprecated practices is naming object-oriented programming class constructor methods with the name of the class. (Search through the code for the constructor, it can be anywhere in the class.)

Here’s an example of this deprecated code:
class CSS_Color extends PEAR {
  function CSS_Color($fgHex, $bgHex='', $minbdif=0, $mincdif=0) {

That gives a warning:
PHP Deprecated:  Methods with the same name as their class will not be constructors in a future version of PHP; CSS_Color has a deprecated constructor in /FOLDERNAME/csscolor.php on line __

The fix for this is amazingly easy.
class CSS_Color extends PEAR {
  function __construct($fgHex, $bgHex='', $minbdif=0, $mincdif=0) {

(That is two underscore _ characters, followed by ‘construct’)

This is an improvement in the language, allowing a well-named class to have the name of the class as a function that could be used; the constructor has a special name.

Here’s another example:

PHP Deprecated:  Methods with the same name as their class will not be constructors in a future version of PHP; GeSHi has a deprecated constructor in /USERFOLDER/public_html/wp-content/plugins/wp-geshi-highlight/geshi/geshi.php on line 259

class GeSHi {
  function GeSHi($source = '', $language = '', $path = '') {

Change that to

  function __construct($source = '', $language = '', $path = '') {


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.