When and where to instantiate a class?

Asked

Viewed 42 times

0

When performing the project, it is recommended to instantiate a Class in the file where it is implemented

(Ex.: "classname.Class.php"),

causing it to be instantiated even without being used in the system at various times

OR

only when they need to access some method from it?

  • 1

    Only create an object when using.

1 answer

2


You should instantiate an object only when using, for example: A Car class where you need to store the card and use some method of it.

Class loading

But in your example you gave the idea of importing a class to your PHP file and really this is a problem since you will be loading items that at that time will not use, besides having to fill your include code.

For this second case, PHP has the spl_autoload_register, an Autoloading that already do all this service for you. I’ll leave the Autoloading documentation link below so you can get more in-depth about.

http://php.net/manual/en/language.oop5.autoload.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.