Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class be static in php [duplicate]

Tags:

php

class

static

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 class StaticClass
{
    public static function staticMethod()
    {
        return 'foo';
    }
}

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

like image 437
Neelesh Avatar asked Aug 12 '26 22:08

Neelesh


2 Answers

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.

like image 78
BoltClock Avatar answered Aug 15 '26 13:08

BoltClock


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
}
like image 36
ircmaxell Avatar answered Aug 15 '26 11:08

ircmaxell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!