Static classes in PHP via abstract keyword?

后端 未结 10 1953
孤独总比滥情好
孤独总比滥情好 2021-01-31 19:00

According to the PHP manual, a class like this:

abstract class Example {}

cannot be instantiated. If I need a class without instance, e.g. for

10条回答
  •  既然无缘
    2021-01-31 19:36

    As other guys said, you cannot instantiate an abstract class. You could use static methods in your class to prevent instantiating, but I'm not really a fan of doing so unless I have a proper reason.

    I might be little bit off-topic now, but in your example you said you wanted this for Registry pattern class. What is the reason you don't want to instantiate it? Wouldn't it better to create an instance of Registry for each registry you want to use?

    Something like:

    class Registry {
        private $_objects = array( );
    
        public function set( $name, $object ) {
            $this->_objects[ $name ] = $object;
        }
    
        public function get( $name ) {
            return $this->_objects[ $name ];
        }
    }
    

    I wouldn't even use Singleton in this case.

提交回复
热议问题