johnsmith153 Posted July 14, 2010 Share Posted July 14, 2010 Which of these is the best way to program in PHP when usng classes? Please explain why and only answer if you are 100% sure, not just what you actualy do. Example is for a site with 50 or so classes where 1 or 2 will be used per script. (1) Use Autoloading Classes (function __autoload) for EVERY class you need (so you never need to define any classes). (2) Just require_once every class every time (use one include file on the main .php page where a require_once is used for each of 50 classes inside this include file) (3) Ensure every page/script has individual require_once('specificClass.php'); for each needed class for that page/script (slow when creating script of course and may miss some) I like (1), but this seems like it could be wrong (and too easy!). Quote Link to comment https://forums.phpfreaks.com/topic/207755-autoloading-classes/ Share on other sites More sharing options...
wildteen88 Posted July 14, 2010 Share Posted July 14, 2010 This is what the magic function __autoload is for. It will only include the necessary classes your code will require. However you can of course do this manually though. But there is no point including all classes and only using two or three at a time. Quote Link to comment https://forums.phpfreaks.com/topic/207755-autoloading-classes/#findComment-1086060 Share on other sites More sharing options...
Mchl Posted July 14, 2010 Share Posted July 14, 2010 (4) using spl_autoload Quote Link to comment https://forums.phpfreaks.com/topic/207755-autoloading-classes/#findComment-1086063 Share on other sites More sharing options...
johnsmith153 Posted July 14, 2010 Author Share Posted July 14, 2010 I don't see the need for spl_autoload. Should I? I will always know the class name: function __autoload($class) { //then just load the .php file for $class (e.g. Database.php) } Quote Link to comment https://forums.phpfreaks.com/topic/207755-autoloading-classes/#findComment-1086081 Share on other sites More sharing options...
Mchl Posted July 14, 2010 Share Posted July 14, 2010 The point of spl_autoload is that: 1. You don't implement your own function -> one less place to introduce bugs 2. It's a standard solution 3. Since PHP5.3 it works very well with namespaces (write your own implementation? I dare you ) Quote Link to comment https://forums.phpfreaks.com/topic/207755-autoloading-classes/#findComment-1086085 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.