H
H
Hazrat Hajikerimov2014-08-15 20:58:57
PHP
Hazrat Hajikerimov, 2014-08-15 20:58:57

Why does a static class need to have a constructor method?

I am interested in the moment with a static class, by and large I use classes as a set of data with methods and, if necessary, refer specifically to some method, but when I create a class without a constructor, it is a static class, php gives an error.
Code example:

class Router {
    static protected $url;
    static protected $path;

    static public    $param = array();
    static public    $page;

    public function __construct(){
        
    }
    static function url() {
        self::$url = parse_url('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        self::$path = explode('/',self::$url['path']);

        foreach (self::$path as $el) {
            if (empty($el)){continue;}
            self::$param[] = urldecode(trim($el));
        }

        self::$param[0] = !isset(self::$param[0]) ? 'show' : self::$param[0];
        self::$page     = self::$param[0];
    }

    static function router (){
        $sql = SQL::getInstance();
        $sql->where(false,'page');
        $sql->add('page',self::$page);
        $sql->query();

        if ($sql->sum()){
            include PATH;
        }else{
            include HOME;
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-08-15
@hazratgs

It is not clear why you need a class here at all ...
If you write a class, do not use statics. Generally. Static methods can facilitate access to an object, you can put some simple initialization logic there (factories as static methods), but just block statics ...
As for the obligatory presence of a constructor, it is not necessary. The problem is in the static method router, which has the same name as the class and is treated as a constructor. But a constructor cannot be static. When you explicitly define a constructor, the problem "disappears"...
This is what mistakes tell you, learn to read them. Alternatively, just rename it to handleRoute or something.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question