开发者

Can a class be static in php [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Is it possible to create static classes in PHP (like in C#)?

Can any one tell me if a php class can be declared as static ?

static clas开发者_开发百科s StaticClass
{
    public static function staticMethod()
    {
        return 'foo';
    }
}

This code giving me error.parse error: parse error, expecting `T_VARIABLE'


No, you can't explicitly declare a PHP class as static.

You can make its constructor private so attempting to instantiate it (at least from outside the class) causes fatal errors.

class StaticClass
{
    private function __construct() {}

    public static function staticMethod()
    {
        return 'foo';
    }
}

// Fatal error: Call to private StaticClass::__construct() from invalid context
new StaticClass();

If you're looking to implement static initialization and other features found in C# static classes, see the other linked question. Otherwise if all you want is to group some utility methods into a class, simply privatizing the constructor should do the trick.


One other alternative is to create the class as abstract. While it still can be extended and instantiated, it can't directly be.

abstract class test {
    public static function foo() {
    }
}

$foo = new test(); // Fatal error, can't instantiate abstract class

If you go with a private constructor, I'd suggest also making it final, since otherwise an extending class can override it and actually instantiate the class (as long as it doesn't call parent::__construct():

class test {
    private final function __construct() {}
}
class test2 extends test {
    public function __construct() {} // fatal error, can't extend final method
}


You can declare a variable as static, and a method, but not a class:

static public $stat_sample = 'test';

static public getSample() {
 return "test";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜