PHP Inherit the properties of non-class object?

PHPServer Side ProgrammingProgramming

For this, use clone along with set the property name to null.

Example

The PHP code is as follows

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$firstObject = (object)[
   "Name"  => "John",
   "Age"  => 20
];
$secondObject = clone $firstObject;
var_dump($firstObject);
echo "<br>";
var_dump($secondObject);
foreach ($secondObject as $keyName => $keyValue) {
   $secondObject->$keyName = null;
}
echo "<br>";
var_dump($secondObject);
$firstObject = [
   "Name"  => "John",
   "Age"  => 20
];
echo "<br>";
$arrayObject= array_fill_keys(array_keys($firstObject), null);
$secondObject = (object)$arrayObject;
var_dump($secondObject);
?>
</body>
</html>

Output

This will produce the following output

object(stdClass)#1 (2) { ["Name"]=> string(4) "John" ["Age"]=> int(20) }
object(stdClass)#2 (2) { ["Name"]=> string(4) "John" ["Age"]=> int(20) }
object(stdClass)#2 (2) { ["Name"]=> NULL ["Age"]=> NULL }
object(stdClass)#1 (2) { ["Name"]=> NULL ["Age"]=> NULL }
raja
Updated on 13-Oct-2020 07:14:18

Advertisements