NYCPHP Meetup

NYPHP.org

[nycphp-talk] Accessing a method from one class in another

Mikko Rantalainen mikko.rantalainen at peda.net
Thu Jan 19 09:21:36 EST 2006


David Mintz wrote:
> If you're using PHP 5, one nice thing about the good old singleton is you
> can get your instance from any scope.
> 
> $db = MyDatabaseClass::getInstance() ;
> 
> //// from MyDatabaseClass
> 
> private static $instance = null;
> 
> public static function getInstance() {
> 
>     if (is_null(self::$instance)) {
> 	// this uses PEAR and relies on an __autoload
>         self::$instance = DB::connect("$driver://$user:$password@$host/$db");
> 	if (DB::isError(self::$instance)){
>             trigger_error('could not connect to database',E_USER_ERROR);
> 	}
> 	self::$instance->setFetchMode(DB_FETCHMODE_ASSOC);
> 	// et cetera
>     }
>     return self::$instance;
> }

If you only have PHP4, you can still do something like this

//// from MyDatabaseClass

function &getInstance()
{
     static $instance = 0;
     if (!$instance) {
	// this uses PEAR and relies on an __autoload
         $instance = DB::connect("$driver://$user:$password@$host/$db");
	if (DB::isError($instance)){
             trigger_error('could not connect to 
database',E_USER_ERROR);
	}
	$instance->setFetchMode(DB_FETCHMODE_ASSOC);
	// et cetera
     }
     return $instance;
}

(the above is untested but should work, you might need to adjust the 
code that connects to database).

-- 
Mikko



More information about the talk mailing list