Reputation: 21
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......
Upvotes: 2
Views: 1676
Reputation: 562631
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();
}
}
Upvotes: 4
Reputation: 317119
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.
Upvotes: 1
Reputation: 75629
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.
Upvotes: 2