Common PHP mistakes
From Dokeos
Global variables
PHP functions don�t work the way you would expect coming from almost any other programming language. PHP functions have no access to global variables, unless in the function code block you explicitly declare the needed variables as global $varname. This is the source of many bugs and a lot of frustration�
$text_string = "Hello world";
function write_output()
{
echo $text_string; //this will not produce any output
}
function write_output_improved()
{
global $text_string;
echo $text_string; //this will work
}
On the other hand, it can be thought of as a forcing device: since using global variables directly is awkward, try to write accessor functions to reach them. Don't use $mainDatabase, instead, write a separate function get_main_database(). Or add the needed "globals" to the parameter list. <sarcasm>And if the parameter list gets too long, switch to an object oriented programming language</sarcasm>.
Semi-colon after if-line
Consider the following code
if ($action == "create_virtual_course");
{
display_create_virtual_course_form();
}
this piece looks fine, however, the first line ends with a semi-colon (;) and thus terminates the if sequence. This means the code block { ... } after it is always executed. The correct code should be
if ($action == "create_virtual_course")
{
display_create_virtual_course_form();
}
This problem can occur with all of the following control structures:
- if
- while
- for
- foreach
- switch
- declare

