tags:

views:

31

answers:

4

-------Now, another question

class DBFactory {  
                static function create(){  
                return new MysqlDB();  
        }  
    }  
class MysqlDB{ 
    function alo(){  
        echo 'ok';  
        }
}  
$db = DBFactory::create();  
$db->alo();  

--->Works

class DBFactory {  
                function create(){  
                return new MysqlDB();  
        }  
    }  
class MysqlDB{ 
    function alo(){  
        echo 'ok';  
        }
}  
$db = new DBFactory;  
$db->create();  
$db->alo();    

--->Not works, can anyone explain?

A: 

DBFactory does not have a method alo, does it?

This would work:

$dbFactory = new DBFactory;  
$db = $dbFactory->create();  
$db->alo();   
Pekka
`Undefined variable on line 2: $db` ;P
deceze
@deceze argh, corrected :)
Pekka
Thanks Everybody
Snoob
A: 

Because you're returning a new MysqlDB instance, but are not saving the reference anywhere. DBFactory does not have an alo method. Compare:

$db = new DBFactory;  
$mysqlDb = $db->create();  
$mysqlDb->alo(); 
deceze
Thanks, i Understood
Snoob
A: 

DbFactory is returning an object, and not internally assigning it!

class DBFactory
{
    function create(){  
        return new MysqlDB();  
    }  
}  
class MysqlDB
{
    function alo()
    {
        echo 'ok';  
    }
}
$db = new DBFactory;  
$Database = $db->create();  
$Database->alo();

if you wish to keep it like in the same object then do

class DBFactory
{
    var $DB;
    function DBFactory()
    {
        $this->DB = new MysqlDB();  
    }
    function __call($name,$arguments)
    {
        return call_user_func_array(array($this->DB,$name),$arguments);
    }
}  
class MysqlDB
{
    function alo()
    {
        echo 'ok';  
    }
}
$db = new DBFactory;
$db->alo();
RobertPitt
A: 

Factories are usually abstract and thus can't be instantiated. They have one or more static methods which create objects for you. So there is no need to instantiate a factory.

The (static) create() method returns an instance of MysqlDB, you are just calling the method without assigning the result to a variable so it just gets 'lost'.

For the specific solution see @deceze's answer.

Dennis Haarbrink