Can a class be static in php

Possible duplicate:
Is it possible to create static classes in PHP (for example, in C #)?

Can someone tell me if php class can be declared as static?

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

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

+3
source share
3 answers

No, you cannot explicitly declare a PHP class static.

You can make your constructor private, so trying to create one (at least from outside the class) leads to 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();

, #, . . , , , , .

+6

- abstract. - , .

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

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

, final, ( parent::__construct():

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

static , :

static public $stat_sample = 'test';

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

Source: https://habr.com/ru/post/1780873/


All Articles