1

Does the __autoload() function ( PHP ) have to be a standalone function or can it be used within a class as a public/protected/private function?

I heard that it has to be a stand-alone function and shouldn't be used in a class. Is this true or can it be used in classes?

Thanks in advance!

3 Answers 3

5

You can use SPL for that:

class MyAutoloader
{
    public static function register()
    {
        spl_autoload_register(array(new self, 'autoload'));
    }

    public static function autoload($classname)
    {
        // auto load code
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have only just accepted an answer so I have to wait 8 mins to accept yours too :P
4

See __autoload() documentation, which says:

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

If you need some example of how to use method of some class as autoloader mechanism, see this example.

Comments

3

What would be the point in having __autoload() in some random class you make?

__autoload() gets invoked when you try to instantiate an object from a class that hasn't been defined yet (spl_register_autoload() is preferred over __autoload()).

Therefore, it has to be globally available. PHP doesn't know that class XYZ contains a function named __autoload() that you want to invoke.

What you can do is create a class that handles autoloading and then use spl_autoload_register() function to have your class called upon the need for autoloading.

1 Comment

"__autoload() gets invoked when you try to instantiate an object from a class that hasn't been defined yet" That's the point. My class uses various other methods from other classes as it is an 'interface' between my site and the FileMaker API to make life easier. So I wanted to init' any class that would be used. Thanks for the input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.