Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict what can create a PHP Class

I got two classes, "A" and "B". In the application logic no one is allowed to create an object of class "B", except for class "A". But, since I dont want to have the two classes in the same file I cant restrict it with the "private" properity.

Is it possible to create this kind of restriction? If someone other then "A" tries to create an object of class "B", you say piss off!?

like image 532
Emil Avatar asked Oct 15 '10 15:10

Emil


People also ask

How do I restrict an instance of a class?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.

Can you create a class in PHP?

Define Objects Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword.

What is protected function in PHP?

protected - the property or method can be accessed within the class and by classes derived from that class. private - the property or method can ONLY be accessed within the class.


1 Answers

This is as hacky as it get's and you should not use it. I only post it, because I like hacky things ;) Furthermore this will throw an error if E_STRICT error reporting is enabled:

class B
{
    private function __construct() {}

    public function getInstance() {
        if (!isset($this) || !$this instanceof A) {
            throw new LogicException('Construction of B from a class other than A is not permitted.');
        }

        return new self;
    }
}

class A
{
    function someMethod() {
        $b = B::getInstance(); // note that I'm calling the non-static method statically!
    }
}

The reason why this works is a "feature" which may be seen in the second example of this manual page.

like image 188
NikiC Avatar answered Oct 19 '22 14:10

NikiC