Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create object of the same class that passed object in php

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?

like image 285
user3125758 Avatar asked Feb 11 '23 21:02

user3125758


2 Answers

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));
like image 88
AbraCadaver Avatar answered May 04 '23 23:05

AbraCadaver


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 ( )
like image 28
Rizier123 Avatar answered May 05 '23 00:05

Rizier123