1

In PHP, I'm reading some data from a normalization table in a database, and depending on which columns are non-NULL, I need to create certain objects. Something along the lines of:

if (!empty($fridge_contents[0])) {
  require('Cheese.php');
  $someCheese = new Cheese;
}

Conditional instantiation is normal, but is it bad practice to conditionally read in your class code as you need it like this? Should I require the class code in global scope rather than in a conditional block? Response time is pretty critical, so I'd prefer not to load every possible class of object in memory if I'm only going to be instantiating a small subset.

Escher
  • 5,418
  • 12
  • 54
  • 101
  • 1
    You should look at using an [autoloader](http://php.net/manual/en/language.oop5.autoload.php). It does the include for you. – Styphon Feb 20 '15 at 14:24
  • @BeatAlex actually you're wrong with `new Cheese();`. It's better to *not* include the brackets if you're not passing any arguments in. – Styphon Feb 20 '15 at 14:25
  • I didn't know that! Thanks I'll read up on it more! @Styphon – Albzi Feb 20 '15 at 14:25
  • 3
    @BeatAlex [This should help](http://stackoverflow.com/questions/1945989/php-class-instantiation-to-use-or-not-to-use-the-parentheses) – Styphon Feb 20 '15 at 14:26
  • 1
    I prefer to leave the brackets in @Styphon: it looks to me like laziness (the bad kind rather than the Perl kind) to omit them. So, at least it is not "better", since it is completely subjective. – halfer Feb 20 '15 at 14:30
  • @halfer Just looks tidier to me, but then that's why there's the option. You can leave them or take them based on your preference (or conventions) – Styphon Feb 20 '15 at 14:31
  • Escher, switch the `require` to `require_once`, so you don't get a fatal error if you include the same file twice. – halfer Feb 20 '15 at 14:32
  • 1
    @Halfer That's actually a bad idea. If you `require_once` then it can affect performance (as it stores and checks against each included file), it's much better to ensure that you only call the code once. You should have your code working properly, not relying on PHP to take care of things for you. – Styphon Feb 20 '15 at 14:34
  • We will have to agree to disagree on that point, @Styphon. You're right about the auto-loader, though! – halfer Feb 20 '15 at 14:37

0 Answers0