Home Variables

Variable "Declaration"

PHP has no concept of "declaring" a variable without initializing it. A statement such as the following is useless and should not be included in your code.

$employees;   # these statements do nothing
$todays_date; #they do not actually declare variables

Variable Scope

Declare variables in the narrowest possible scope. For example, if a variable is used only inside a specific if statement, declare it inside that if statement rather than at the top of the function or the top of the PHP file/class. You should never use the global keyword, which allows functions to have access to global variables. Instead, pass parameters to the function and/or return a value from the function.

$students = 4;
$money = 2;
process_classroom();
...
function process_classroom() {
  global $students;
  global $money;
  print($students);
  $money = 5;
}
$students = 4;
$money = 2;
$money = process_classroom($students);
...
function process_classroom($stud) {
  print($stud);
  return 5;
}

Saving Expensive Calls Into Variables

If you are calling an expensive function and using its result multiple times, save that reuslt in a variable rather than having to call the function multiple times.

if (strlen(file_get_contents("foo.txt")) >= 0 &&t;
    file_get_contents("foo.txt") != "hello") {
  $text = strtolower(file_get_contents("foo.txt"));
}
$text = file_get_contents("foo.txt");
if (strlen($text) >= 0 && $text != "hello") {
  $text = strtolower($text);
}