I have the fallowing situation
class A {
...
public static function Copy($obj) {
$newObj = new (class of $obj);
...
}
}
class B extends A {
...
}
class C extends A {
...
}
...
$newB = B::Copy($BObject);
$newC = C::Copy($CObject);
Can I create a new object of the parameters class, or I have to override method for every inherited class?
May be able to simplify it, but get_class()
is the way to go:
$class = get_class($obj);
$newObj = new $class;
I couldn't find a one-liner for PHP 5.x or 7.x, but this appears to work in PHP 8.0:
$newObj = new (get_class($obj));
I think something like this should work for you:
(Here i use get_called_class()
to get the class name which is calling the method)
<?php
class A {
public static function Copy() {
$class = get_called_class();
return $newObj = new $class;
}
}
class B extends A {
}
class C extends A {
}
$newB = B::Copy();
print_r($newB);
$newC = C::Copy();
print_r($newC);
?>
Output:
B Object ( )
C Object ( )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With