Skip to content
Advertisement

PHP inherit the properties of non-class object

Is it possible to inherit the properties of a non-class object to another variable?

<?php
    
  $obj1 = (object)[
      "prop1"  => "String",
      "prop2"  => "INT"
  ];

  $obj2 = new $obj1;  
  var_dump($obj2->prop1);  // output : Notice: Undefined property: stdClass::$prop1

?>

I can do instead:

  $obj2 = $obj1;    // But, I don't want to pass value. I want properties only with no value or null

Advertisement

Answer

Though I can’t imagine situation where you need this, still I think of 2 workarounds to get the copy of an object with nulled props:

  // First one: clone object and unset properties via `foreach`
  $obj1 = (object)[
      "prop1"  => "String",
      "prop2"  => "INT"
  ];

  $obj2 = clone $obj1;
  foreach ($obj2 as $propName => $propValue) {
      $obj2->$propName = null;
  }
  var_dump($obj2);
  
  // Second: create new array with keys from original array 
  // and null-values and then convert this array to object
  $obj1 = [
      "prop1"  => "String",
      "prop2"  => "INT"
  ];
  $newArray = array_fill_keys(array_keys($obj1), null);
  $obj2 = (object)$newArray;
  var_dump($obj2);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement