Wednesday, August 17, 2011

__autoload() in php 5


When writing object-oriented code, it is often customary to put each class in its
own source file. The advantage of this is that it’s much easier to find where a
class is placed, and it also minimizes the amount of code that needs to be
included because you only include exactly the classes you need. The downside
is that you often have to include tons and tons of source files, which can be a
pain, often leading to including too many files and a code-maintenance headache.
__autoload() solves this problem by not requiring you to include classes
you are about to use. If an __autoload() function is defined (only one such function
can exist per application) and you access a class that hasn’t been defined,
it will be called with the class name as a parameter. This gives you a chance to
include the class just in time. If you successfully include the class, your source
code continues executing as if the class had been defined. If you don’t successfully
include the class, the scripting engine raises a fatal error about the class
not existing.
Here’s a typical example using __autoload():
MyClass.php:
<?php
class MyClass {
function printHelloWorld()
{
print "Hello, World\n";
}
}
?>
general.inc:
<?php
function __autoload($class_name)
{
require_once($_SERVER["DOCUMENT_ROOT"] . "/classes/
➥$class_name.php");
}
?>
main.php:
<?php
require_once "general.inc";
$obj = new MyClass();
$obj->printHelloWorld();
?>


source PHP 5 Power Programming
Andi Gutmans, Stig Sæther Bakken,
and Derick Rethans

What is difference between require_once(), require(), include() ?

Difference between require() and require_once():  require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).
So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING.

There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

MS in Computer Science with paid training in USA company