in PHP, is there is there a way to differentiate when magic method is called through a PHP construct or directly?
E.g.: public function __clone() {}
is called each time an object is cloned through the clone
keyword:
$a = new ObjectA();
$clone = clone $a; // Calls __clone()
However, someone can even (do not know why someone should do that, but, anyway) call __clone()
directly:
$a = new ObjectA();
$clone = $a->__clone(); // Call __clone() directly
Same goes for other PHP magic methods (__call()
, __debugInfo
, etc.).
Can we differentiate between the two cases somehow?
Thank you for the attention!
EDIT: Assume the following scenario:
I have a dynamic proxy class, which extends a base class and internally creates an instance of the base class only when the object is effectively used:
class A {
...
public function __clone() {
echo "clone A!!!";
}
...
}
class DynamicProxy extends A {
protected $a = NULL;
public function __clone() {
$this->createA();
if ( /* __clone() is triggered by `clone $obj`, I need to clone $a: */ ) {
clone $this->a;
}
else {
// But if someone, for some reason (I do not now why, but it could be, and I would like to be consistent), have called `$obj->__clone();`, I do not have to call `clone $obj`, but proxy the call:
return $this->a->__clone();
}
}
protected function createA() {
if (is_null($this->a)) {
$this->a = new A();
}
}
}
$obj = new DynamicProxy();