What is define used for? It is for defining constants but why not just use a string?
Printable View
What is define used for? It is for defining constants but why not just use a string?
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;
}
?>
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. :)Quote:
Originally Posted by dclamp
Edit: There seems to be a few differences that I didn't think of, like placing one directly in a string.
And there's also a case-sensitive argument in Define().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
You may want to look here for more info:
http://us3.php.net/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
}
ah! that makes sense.
thanks for elaborating va