Jump to content

Best place to instantiate new object


dgruetter

Recommended Posts

Hi,

 

I am trying to find the best location to instantiate a new object in my code. My old method was to instantiate a new object at the bottom of the class declaration.

 

class Messenger () {

//class structure

}//Close class

$messenger = new Messenger();


 

I just built an initialize script to simplify all the requires. It also has an autoload function for classes like messenger that might not need to be required and instantiated on every page

 

function __autoload($class_name) {
global $MODELS_DIR;


    require ($MODELS_DIR . $class_name . '.php');

}

 

The problem is that if I instantiate a new class Messenger() at the end of my class declaration, it will never autoload... because I am not calling for a new Class() in my code.

 

So should I continue to instantiate at the end of the class declaration of always instantiate it in my code?

 

Not sure if it's worth mentioning but I plan on moving my code to a MVC framework in the future.

 

Oh yeah, I am also using PHP 5.29 ... I think

Link to comment
Share on other sites

No. You shouldn't really be doing that at all.

 

Autoloading only happens when you try to reference a class (like instantiating it or something else I forget) and if the class's file hasn't been included it. If you require() the file then try to instantiate it the autoloading stuff won't fire - it's already been loaded. Your class files should just have the class definition with very few exceptions. Make an autoloader using spl_register_autoload() (__autoload() is deprecated) that includes the appropriate file when the class is requested. Then every time you need the class you try to use it.

And if you only want one instance of a class around then you should be using a Singleton, not a pre-instantiated class.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.