How do you refuse to create an instance copy in PHP?

In the past, at one interview, I had a test question: "How do you refuse to create a copy of an instance of a class (object)?".

My answer was to use the Singleton patter in the first place, when it denies instantiating at all.

But when I recently thought about it, I think it was not the best answer. Now I think that using a class privatefor a class method __clone()would be a better solution. Thus, it allows you to at least create a new instance.

But I think there is another way to do this? If Singleton is not used or no closed area is set, is there any best practice how to deny instantiating an instance?

+4
source share
1 answer

There is one more option. When you close your __clone () private account, the following will be called when cloning:

PHP7.x FATAL ERROR Uncaught Error: calling private A :: __ clone () from context

PHP5.x FATAL ERROR Call private A :: __ clone () from context

So, if you want your code to behave exactly the same among different versions of PHP, you can do the following:

<?php

class A {
    public function __clone() {
        throw new Exception('Not allowed to be cloned');
    }
}

$a = new A;
try {
    $b = clone $a;
} catch (Exception $e) {
    echo $e->getMessage(); //Not allowed to be cloned
}

Or more "fancy":

trait NotClonable {
    public function __clone() {
            throw new Exception('Not allowed to be cloned');
    }
}
class A {
    use NotClonable;
}
+2
source

Source: https://habr.com/ru/post/1655734/


All Articles