Skip navigation

Tag Archives: overloaded

Q: How do I do an overloaded constructor in PHP?

A: You don’t need them

Consider the following

class Foo
{
  var $name ;
  function __construct()
  {
    # if the default ctor is invoked, name
    # this instance "unnamed"
    $this->name = 'unnamed' ;
  }

  # Fine and dandy, but what if
  # we want to supply a name
  # in an overloaded ctor?
  
  function __construct( $iname )
  {
    $this->name = $iname ; #doesn't work
    # because overloaded ctors of this style
    # aren't supported in PHP!!
  }
  
}

OK. Well I promised in the title of this post that you didn’t need overloaded constructors in php Here’s why.

Redefine class Foo as follows:


class Foo
{
  var $name ;

  # specify a single ctor, WITH DEFAULT VALUES
  # FOR PARAMETERS.  This is equivalent, and in my
  # opinion a better syntax
  # for getting overloaded constructors to work.
  function __construct( $iname = 'unnamed' )
  {
    $this->name = $iname ;
  }
}

There. Fewer lines of code, less mess, same effect. This was an excellent design decision by the php group.