There is another useful thing to know related to variables and variable scope:
Often PHP programmers like to include() a central config file to place all the "application-level" variables, something like:
Code:
<?php
$hostname = "[URL unfurl="true"]www.thiswebsite.com";[/URL]
$mysql_user = "myusername";$mysql_passwd = "mypassword";
$mysql_db = "mydatabasename";
?>
Then you just include this page at the top of every PHP file and you only have to change your password or databasename in one place, instead of every page. So far this is standard stuff everyone knows. The only problem is, these shouldn't be variables, they should be
constants. (
Constants are a much better choice for this kind of data for several reasons:
1) they automatically have global scope, so you can use them inside any function or code block, without using the "global" keyword.
2) once defined, a constant is unchangeable by the script, so there is no chance of a "cracker" messing with that variable by playing with URL parameters.
3) They use less system resources than regular variables, because the system does not need to track their changes.
Thus the code I show above should actually look like:
Code:
<?php
define ("HOSTNAME", "[URL unfurl="true"]www.thiswebsite.com");[/URL]
define ("MYSQL_USER" = "myusername");
define ("MYSQL_PASSWD" = "mypassword");
define ("MYSQL_DB" = "mydatabasename");
?>
Constants do not have to be in all capitals, but that is the recommended usage, for code readability. You don't use the "dollar sign" notation, but just bare text:
mysql_connect(HOSTNAME, MYSQL_USER, MYSQL_PASSWD);