|
-
Apr 4th, 2008, 03:04 PM
#1
Thread Starter
WiggleWiggle
define()
What is define used for? It is for defining constants but why not just use a string?
My usual boring signature: Something
-
Apr 4th, 2008, 04:31 PM
#2
Re: define()
You could just use a variable, but when I make something like a vars.php file to store settings, I personally use define().
Also, since "definitions"/constants, whatever, don't require you to use a $ sign, it helps distinguish them from other variables.
PHP Code:
<?php
define('DB_HOST','localhost');
define('DB_USER','username');
define('DB_PASS','password');
define('DB_NAME','digirev');
function db_connect() {
$f_dbc = @mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
return $f_dbc;
}
?>
-
Apr 4th, 2008, 04:42 PM
#3
Thread Starter
WiggleWiggle
Re: define()
so there is really no difference to using defined constants and strings?
i think they look alot better than strings, personally.
thanks Digi!
My usual boring signature: Something
-
Apr 4th, 2008, 04:52 PM
#4
Re: define()
 Originally Posted by dclamp
so there is really no difference to using defined constants and strings?
i think they look alot better than strings, personally.
thanks Digi!
You're welcome. 
Edit: There seems to be a few differences that I didn't think of, like placing one directly in a string.
PHP Code:
echo "DB host is $DB_HOST"; // would work if $DB_HOST was a variable echo "DB host is DB_HOST"; // will not work with constant
And there's also a case-sensitive argument in Define().
You may want to look here for more info:
http://us3.php.net/define
Last edited by DigiRev; Apr 4th, 2008 at 04:56 PM.
-
Apr 4th, 2008, 04:58 PM
#5
Re: define()
A constant remains constant unlike a variable which can be changed. Once a constant is defined it cannot be changed. Constants are usually defined at design time but in PHP global constants can be defined at run time and given dynamic values (i.e: expressions containing values derived from mathematical operations, functions or variables).
Class constants are however are real constants as they can only be defined at design time and must be a constant expression only.
PHP Code:
define ('MY_CONST', 1); // valid define ('MY_CONST1', $GLOBALS['my_var']); // valid
class Test { const MY_CONST = 1; // ok const MY_CONST1 = $GLOBALS['my_var']; // invalid }
Last edited by visualAd; Apr 4th, 2008 at 06:06 PM.
-
Apr 4th, 2008, 05:13 PM
#6
Thread Starter
WiggleWiggle
Re: define()
ah! that makes sense.
thanks for elaborating va
My usual boring signature: Something
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|