开发者

How do we stop object creation by the user of class in PHP?

I want to stop object creation by the user of class "OzoneRequest" and "OzoneResponse"in 开发者_如何学运维PHP . Only one object is created at OzoneApplication's constructor. How I'll do this? May be you understand my question

I do not want creation of object by the user Only I create an object that only one object exist. If user want to create object then this will not be performed... this will give an error......


class OzoneRequest
{
 private static $instance = null;

 private function __construct() { }

 private function __clone() { }

 public static function getInstance()
 {
   if (!isset(self::$instance)) {
     self::$instance = new OzoneRequest();
   }
   return self::$instance;
 }

}

class OzoneApplication
{
  protected $req;

  public function __construct()
  {
    $this->req = OzoneRequest::getInstance();
  }

}


Make a private constructor, then call this from a static method within the class to create your one object. Also, lookup the singleton design pattern.


That would be the UseCase for a Singleton.

However, I do not see the point in restricting the User (read: the developer) to not create a Request or Response object if he wants to. Even if conceptually there is only one Request object (which is arguable; what if I need to dispatch multiple Requests against a remote service), the question is: why do you forbid a developer to change your code? I am a grown-up. If I want to break your code, let me break it.

Also note that the Singleton pattern is widely regarded an Anti-Pattern nowadays.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜