PHP blog - Autoload
I detest php websites with many include files. I see a function and wonder where that function is defined at. I've often had to run a search on the entire website to find out where it's defined. Some sites have include files that include other include files. Then, there are the conflicts where two different include files will require the same third include file.
Well, PHP has an easy way around that: spl_autoload_register. If I use a class that hasn't been included yet, the spl_autoload_register function runs with the name of the class. I write a function that loads the php file for that class. The function knows the name of the php file because it's the same name as the class, but with a .php suffix. I use an App_Code folder because Asp.Net has a similar concept.
Here's the one and only include I put as the first line of every .php file:
<?php require "App_Code/autoload.php"; ?> Here's my autoload.php file:
// The idea of autoload is that a function is called whenever
// a class is used that PHP doesn't recognize. This gives the
// program a chance to load that class. Just make the name of
// the class match the file name of the include file
// containing that class.
// Use public static functions in classes to run a function
// in that class without creating an instance of that class.
function my_autoload($sClassName)
	for($loop=0;$loop < strlen($sClassName);$loop++)
		$thischar = substr($sClassName,$loop,1);
		if (($thischar != "_") && ((!ctype_alnum($thischar)) || (ctype_digit($thischar))))
			echo 'Class ' . $sClassName . ' has invalid characters.';
	$filename = dirname(__FILE__) . '/' . strtolower($sClassName) . '.php';	
	if (file_exists($filename))
	} else
		echo 'Error: file ' . $filename . ' not found looking for class ' . $sClassName;
Global Variables and Global Functions
There are reasons for making global variables and global functions. But there are also reasons for not programming that way. I put functions as static members of classes:
class cCommon
    static $example_global_variable = "Jellyfish";
    public static function Request($field)
      $value = "";
      if (isset($_POST[$field]))
        $value = $_POST[$field];
      } else {
		  if (isset($_GET[$field]))
			  $value = $_GET[$field];
      return $value;
Here's an example of using the above static function:
$employeeName = cCommon::Request("EmployeeName");
Here's the global variable being used:
echo cCommon::example_global_variable;
Below are the list of advantages:
  1. The global variables as properties of a class don't pollute the global namespace.
  2. If you're using an autoload function, the class that contains the global variable or function will be automatically included.
  3. Another developer can tell which include file the class resides in (if you used an autoload function).
  4. It's an object oriented approach.