2

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......

user421336
  • 21
  • 3

3 Answers3

4
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();
  }

}
Bill Karwin
  • 462,430
  • 80
  • 609
  • 762
  • Since this is technically a correct solution, I'll upvote it. Morally it's a different story ;) – Gordon Aug 20 '10 at 16:57
2

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.

Sjoerd
  • 68,958
  • 15
  • 118
  • 167
1

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.

Community
  • 1
  • 1
Gordon
  • 296,205
  • 68
  • 508
  • 534
  • I try to develop a MVC Framework for my college major project i call it as OZONE_MVC(http://code.google.com/p/ozonemvc/), in this when an request is come from client then framework itself create an object of request and response which may must be unique. User use only that object. It is at beginning level..... – user421336 Aug 20 '10 at 16:46
  • @user why do they have to be unique? And how do you expect a *user* to create a second Request or Response? I mean, *users* dont have access to your code. – Gordon Aug 20 '10 at 16:51