Skip to content
Advertisement

PHP: Concatenate classes on each other

How can I concatenate a class onto another class in this manner?

class Person { }
$p1 = new Person();
$p2 = new Person();
$p3 = $p1 . $p2;

Keep in mind that I will always know everything in the class that needs to be concatenated ahead of time, so generalization is not an issue.

Advertisement

Answer

This will concatenate two objects together assuming they’re the same type

<?php

function combine_objects($obj1, $obj2) {
  if (get_class($obj1) !== get_class($obj2)) {
    throw new Exception('Class mismatch');
  }

  $className = get_class($obj1);
  $newObject = new $className;
  foreach(get_object_vars($obj1) as $key => $value) {
    $newObject->$key = $obj1->$key . $obj2->$key;
  }

  return $newObject;
}

class Person {
  public $first;
  public $last;
  public $id;
}

$john = new Person;
$john->first = 'John';
$john->last = 'Smith';
$john->id = 1;


$mary = new Person;
$mary->first = 'Mary';
$mary->last = 'York';
$mary->id = 5;

$p3 = combine_objects($john, $mary);

var_dump($p3);

/*
object(Person)#3 (3) {
  ["first"]=>
  string(8) "JohnMary"
  ["last"]=>
  string(9) "SmithYork"
  ["id"]=>
  string(2) "15"
}
*/
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement