Re: Question on functions

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I'm not certified expert ;-) but what I meant is

Do not use function that writes to the hardcoded global variables:
example:

function db() {
	...
	$GLOBALS['db']=x_open_something($GLOBALS['...'], ...);
	...
}

This function is really... hm... not flexible enough ;-)

It can make the job done well but... what if you need to open second connection? What if you have news data stored on other server or in defferent database under diferent user/password? Hm. What you will do? You probably create function db2(), yes? And what if you need to read page hit statistic from another database? ... db3()? ... db4()? Do you see the problem?

'functions' are pieces of GENERIC code doing the same thing with different input and resulting in possible different output... What you typed was not GENERIC - it was really one-purpose code that didn't need to be placed in function at all... You could simply include content of db() into your log() method and result would be the same...

I recomend to go this way (I modified your code, I didn't test it so typos/mistakes can be there - just showing the idea)...

/* User Defined Variables */
$defined = array( "host" => "localhost", "user" => "user", "pwd" => "password" );
$defined2 = array( "host" => "localhost2", "user" => "user2", "pwd" => "password2" );


logs(db($defined));
logsOnOtherMachine(db($defined2)); // Little bit more flexible so you can use it for other purposes as well


/* Database connection */
function db($cfg) {
if( connection_status() != 0 ) {
$db = @mysql_pconnect( $cfg['host'], $cfg['user'], $cfg['pwd']) or die('connection problem...');
}
return $db;
}


/* Logging function */
function logs($db) {
 global $defined;

 if (!$db) {
	 trigger_error('Connection was not established!', E_USER_ERROR);
	 return false;
 }

 $pagecount = "1";
 $tble = "logs";
 $sql = @mysql_query( "SELECT * FROM ...", $db ) or die( "problem..." );

 // your stuff...
}

function logsOnOtherMachine($db) {
	...
}

----
And if you would be really trying to dig in... have a look at OOP implementation in PHP... After the beginner's pain you will love it ;-)


Hope I helped little.

elixon

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux