Forum Moderators: coopster

Message Too Old, No Replies

Don't understand syntax

I've never seen a parameter passed in this way before

         

SaminOz

12:46 pm on Aug 27, 2009 (gmt 0)

10+ Year Member



Hi all,
I'm just working my way through a book and the following function (that works!) takes the parameter ($dbname='') - at first I thought it was a typo (there are lots in this book, grrrh) but sure enough it works - does anyone recognise what this ='' means? I thought php and javascript passed their arguments in more or less the same way?

function db_connect($dbname='') {
global $dbhost, $dbusername, $dbuserpassword, $default_dbname;
global $MYSQL_ERRNO, $MYSQL_ERROR;

$link_id = mysql_connect($dbhost, $dbusername, $dbuserpassword);
if(!$link_id) {
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = 'Connection failed to the host ' .$dbhost;
return 0;
}
else if(empty($dbname) && !mysql_select_db($default_dbname)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else if(!empty($dbname) && !mysql_select_db($dbname)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}

jatar_k

2:26 pm on Aug 27, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



that is a way to set a default value

if nothing is passed then it will use whatever is set in the declaration.

this syntax can only be used on the last param, if i remember correctly. So if you had more than one param

this would be correct
function db_connect($dbpass, $dbname='') {

where this is not correct
function db_connect($dbpass='', $dbname) {

<added>
[php.net...]

my memory was not fully exact

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

SaminOz

10:21 pm on Aug 27, 2009 (gmt 0)

10+ Year Member



Thank you Jatar. It's a short coming of the text I'm following that they drop things like this in without explanation. much appreciated. thanks. sam.