Andrej Buday
Andrej Buday

Reputation: 609

How do you deny creating copy of instance in PHP?

In past, at one job interview I had test question "How do you deny creating copy of class instance (object)?".

My answer was to use Singleton patter in the first place while it deny creation of instance at all.

But when I was recently thinking about it, I guess it was not the best answer. Now I think using private scope for __clone() class method would be a better solution. This way it allows at least creating new instance.

But I am thinking, is there any other way how to do it? If Singleton is not used or private scope is not set, is there any better practice how to deny creation of copy of instance?

Upvotes: 4

Views: 125

Answers (1)

jakub wrona
jakub wrona

Reputation: 2254

There is another option. Making the __clone() private will cause the following when cloning:

PHP7.x FATAL ERROR Uncaught Error: Call to private A::__clone() from context

PHP5.x FATAL ERROR Call to private A::__clone() from context

So if you want your code to behave exactly the same among different PHP versions you could 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" one:

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

Upvotes: 2

Related Questions