views:

40

answers:

1

i am new on web programming .i am good on c# .net platform on desktop. i tried to understand php and php frameworks but i get confused a little . i understand that a php file can import classes which is in the file into another php file with require_once function. but frameworks doesnt import his own classes with require_once function . i think they do something different which i dont understand.Can someone explain to me please?

+2  A: 

Most frameworks uses a technique called "Autoloading" to automatically resolve and include needed dependencies.

An "Autoloader" is simply a function that is called by PHP when an unknown class is being referenced. That "Autoloader" can either procedurally create the class or simply include it from an external file based on the file name.

The current (PHP 5.1.2 and higher) proper way of doing so is by using spl_autoload_register(). Here is an example of an autoloader:

function autoload_example($className) {
  $normalizedName = strtolower($className);

  if(file_exists('includes/' . $normalizedName . '.inc')) {
    require_once('includes/' . $normalizedName . '.inc');
  } elseif(file_exists('includes/' . $normalizedName . '.inc')) {
    require_once('includes/' . $normalizedName . '.php');
  } else {
    die('Class ' . $className . ' not found');
  }
}

spl_autoload_register('autoload_example');

$myAwesomeObject = new Awesome();

In the example above, PHP will run the "Autoloader" autoload_example when it will hit the reference to the class Awesome.

The "Autoloader" will first try to look for a file include/awesome.inc. If it can find it, it will include it.

If not, it will look for a file called include/awesome.php. If it can find it, it will include it.

If not, it will die() stating that it could not find my Awesome class.

Andrew Moore