Using clases in PHP to store function

Posted by Artur on Stack Overflow See other posts from Stack Overflow or by Artur
Published on 2010-05-25T11:51:41Z Indexed on 2010/05/25 12:01 UTC
Read the original article Hit count: 321

Filed under:

Hello! I need some advise on my PHP code organisation.

I need classes where I can store different functions, and I need access to those classes in different parts of my project. Making an object of this classes each time is too sadly, so I've found a two ways have to solve it.

First is to use static methods, like

class car {
public static $wheels_count = 4;

public static function change_wheels_count($new_count) {
    car::$wheels_count = $new_count;
} }

Second is to use singleton pattern:

class Example {
// Hold an instance of the class
private static $instance;

// The singleton method
public static function singleton() 
{
    if (!isset(self::$instance)) {
        $c = __CLASS__;
        self::$instance = new $c;
    }

    return self::$instance;
}  }

But author of the article about singletons said, that if I have too much singletons in my code I should reconstruct it. But I need a lot of such classes.

Can anybody explain prons and cons of each way? Which is mostly used? Are there more beautiful ways?

© Stack Overflow or respective owner

Related posts about php