PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
However, I cannot for the life of me work out where I am supposed to place this function??? I am unable get it to work in my scripts. I have looked all over the PHP manual - cant find anything about where this function is meant to go
Thanks for your reply Jenk Do you mean that I have to write the autoload function at the top of every page that I wish to use it in? I still cant get it to work. *sigh* What am I doing wrong here please...
<?php
error_reporting(E_ALL);
Echo "hello";
function __autoload($class_name)
{
if (!file_exists($class_name . '.php') { Echo 'file cant be found'; }
require_once $class_name . '.php';
}
new test_class();
?>
Both files are in the same directory.
I get no errors message in test.php - just a white screen. I get no 'file cant be found message'. Incidentally, the "hello" at the top of test.php does not display unless I completely remove the autoload function. What am I doing wrong please? Thanks in advance!
Are you sure the class file is in the same directory as the script which is using it? Includes are relevant to the script loaded in the browser, not to the file which does the include. If you need an include relative to the current file itself:
Shears wrote:I get no 'file cant be found message'. Incidentally, the "hello" at the top of test.php does not display unless I completely remove the autoload function.
That's because you have a syntax error in the autoload function code.
Unless you're trying this on a production server please set
(Sorry. That was a separate point. I probably shouldn't have used the word "So".)
For example, I have the class test_class in test_class.php . If i want to use this class in test1.php, test2.php, test3.php test4.php, it seems I need to write the autoload function in those four files?
When your webserver receives a http request for a php script it creates a new instance of php. This instance parses the script that was requested and starts executing it. If this script includes other script via include/require the source code is "imported" to the same php instance. A function definition is valid for the whole php instance. If the single request is handled the webserver discards the php instance.
You have to define the __autoload() function for each instance of php where you want to use it - that is not necessarily for each single file.