views:

342

answers:

3

Hi,

I am working with PHP and I am wondering how bad practise it is to combine lots of funtions into a class. I am aware of it's not the purpose of classes, but the reason why I would do this is to provide a namespace. How big impact does it make to initiate let's say 10 classes at the execution of a PHP script isntead of let's say 2 or 3?

A: 

You may not be aware that PHP, as of recently, has first class namespace support: http://uk2.php.net/language.namespaces.

Adam Wright
Almost - the latest stable release is 5.2.8; namespaces will be in 5.3.0
Greg
thanks for the heads-up on that one! looking forward to that feature releasing.
thrashr888
+5  A: 

If you're using a php version < 5.3 (and you are probably, so you can't use namespaces) than you could use something like:

<?php
class Foo {
   public static function aStaticMethod() {
       // ...
   }
}

Foo::aStaticMethod();
?>

(copied from the php manual)

I'd say it a function of a class in a way - grouping of functionality.

This won't have any performance related problems with it (you could do it millions of times and you won't even notice - there should be no runtime cost, only a minute extra parsing cost and this is negligible). Modern php frameworks bring in loads of code and internally create a lot of objects - I wouldn't worry about php performance, database performance will almost always hit you first. Make sure your code is readable and maintainable (yes, especially php code ;)) and if that means grouping functions then do it.

"97% of the time premature optimization is the root of all evil", especially when you're doing web pages and not nuclear simulations ;)

Edit: public and static are php5 only, in php<5 you could try:

<?php
class Foo {
   function aStaticMethod() {
       // don't touch $this
   }
}

Foo::aStaticMethod();
?>
Hrvoje Prgeša
+3  A: 

If you're so concerned about performance that loading 10 classes is too slow, then you shouldn't be using PHP.

At the very least, use an opcode cache like APC, and then loading classes shouldn't be a burden at all.

Bill Karwin