Page 1 of 1

Overloading

Posted: Tue Jun 03, 2008 10:03 pm
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?

Re: Overloading

Posted: Tue Jun 03, 2008 10:12 pm
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.