May
May

Reputation: 51

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

Upvotes: 1

Views: 62

Answers (2)

Marcelo Pereira
Marcelo Pereira

Reputation: 61

You can this:

$obj1 = new stdClass;
$obj1->prop1 = "string";
$obj1->prop2 = 1;
$obj2 = clone $obj1;

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

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);

Upvotes: 2

Related Questions