Overloading

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Overloading

Post by SidewinderX »

PHP is giving me a weird error:
Fatal error: Cannot redeclare Mysql::__construct() in /home/john/www/dev/mysql.php on line 11
I've reduced my code to a minimum and I am still receiving the error.

Code: Select all

<?php
 
class Mysql
{
 
    function __construct($host, $user, $pass, $db=false)
    {
 
    }
 
    function __construct($dsn)
    {
 
    }  
   
 
}
 
?>
Does PHP not allow for function overloading?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Overloading

Post by Chris Corbyn »

It can't (and in part doesn't need to) because it's dynamically typed. You can assign null to all the other parameters by default, then try and work out the arguments passed:

Code: Select all

<?php
 
class Mysql
{ 
    public function __construct($host, $user = null, $pass = null, $db=false)
    {
       if ($this->_isDsn($host)) {
          $this->_constructAsDsn($dns);
       } else {
          $this->_constructParameterized($host, $user, $pass, $db);
       }
    }
    
    // ... SNIP ...
 
}
 
Or probably a cleaner solution is to replace the constructor with factories.

Code: Select all

<?php
 
class Mysql
{
    public static function fromDsn($dsn)
    {
      $instance = new self();
      $instance->_constructFromDsn($dsn);
      return $instance;
    }
 
    public static function newInstance($host, $user = null, $pass = null, $db = null)
    {
      $instance = new self();
      $instance->_constructFromParams($host, $user, $pass, $db);
      return $instance;
    }
    
    private function __construct() //Cannot be created with "new" keyword
    {
    }
    
    private function _constructFromDsn($dsn)
    {
    }
 
    private function _constructFromParams($host, $user, $pass, $db)
    {
    }
    // ... SNIP ...
 
}
 
$db1 = MySQL::fromDsn('mysql://localhost/somedb;user=foo;pass=bar');
 
$db2 = MySQL::newInstance('localhost', 'foo', 'bar', 'somedb');
I agree that PHP sucks when it comes to needing multiple method signatures... you almost certainly need to create new names.
Post Reply