0

I have a seamingly simple problem which I can't figure out and I don't know the name of what I'm looking for.

How do I copy data in a simple way to an extending class? Suppose I have this:

class A {
    private string $a;
    private string $b;
    private string $c;
}

class B extends A {
    private DatetimeInterface $completedAt;
}

$a = new A(1, 2, 3); // via an imaginary contruct()

I now have processed A and want to move it to another table B. I want a new B(), but with all the values of A to start with.

// Pseudo code of what I (think I) am looking for:
$b = MagicallyConvertAToB($a);
$b->setCompletedAt(new Datetime());
  • B will always be identical to A, with only one property added. If A changes, B changes.
  • I could just use a construct to set the values, but I prefer something more automatic. I currently just 'copy' the properties one by one, this is doable but feels... cheap.

We've recently started to focus a bit more on proper programming patterns, this feels like there is one we're missing.

Martijn
  • 15,791
  • 4
  • 36
  • 68
  • The TL;DR is that an object is iterable just like an array. There's also [the Reflection Class](https://www.php.net/manual/en/reflectionclass.getproperties.php) if you want to get fancier than a mere `foreach` loop – Machavity May 10 '22 at 13:32
  • Hm, that all feels like setting properties, but programmatically, I was hoping for a more native solution. 3 properties isnt much at all, it's more a nice place to expiriment with proper patterns :) – Martijn May 10 '22 at 13:33
  • If you `foreach` over the properties to be cloned, assign by reference to accomplish the "sync". Note that even if you "clone in the constructor", you should do it by reference if you want to keep it up to date. Otherwise: inject A into B, as in `class B { function __construct($a) { $this->a = $a; } function getFromA($prop} { return $this->a->$prop; } }` (don't have to extend either), then `$b = new B($a);`? Possibly add a magic getter that returns properties as in `getFromA` if you want to call `$b->c` without ever defining `$c` in class B. (That's a hack though.) – Markus AO May 10 '22 at 19:05

0 Answers0