Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP Inherit the properties of non-class object?
In PHP, you can inherit the structure (property names) of a non-class object while resetting the property values to null. This is useful when you need to create a new object with the same properties but empty values.
Method 1: Using clone and foreach
Clone the original object and then iterate through its properties to set them to null −
<?php
$firstObject = (object)[
"Name" => "John",
"Age" => 20
];
$secondObject = clone $firstObject;
echo "Original object:
";
var_dump($firstObject);
echo "\nCloned object:
";
var_dump($secondObject);
// Set all properties to null
foreach ($secondObject as $keyName => $keyValue) {
$secondObject->$keyName = null;
}
echo "\nAfter setting properties to null:
";
var_dump($secondObject);
?>
Original object:
object(stdClass)#1 (2) {
["Name"]=>
string(4) "John"
["Age"]=>
int(20)
}
Cloned object:
object(stdClass)#2 (2) {
["Name"]=>
string(4) "John"
["Age"]=>
int(20)
}
After setting properties to null:
object(stdClass)#2 (2) {
["Name"]=>
NULL
["Age"]=>
NULL
}
Method 2: Using array_fill_keys()
Convert the object to array, extract keys, fill with null values, and convert back to object −
<?php
$firstObject = [
"Name" => "John",
"Age" => 20
];
// Create array with same keys but null values
$arrayObject = array_fill_keys(array_keys($firstObject), null);
$secondObject = (object)$arrayObject;
echo "Original array:
";
var_dump($firstObject);
echo "\nNew object with inherited structure:
";
var_dump($secondObject);
?>
Original array:
array(2) {
["Name"]=>
string(4) "John"
["Age"]=>
int(20)
}
New object with inherited structure:
object(stdClass)#1 (2) {
["Name"]=>
NULL
["Age"]=>
NULL
}
Comparison
| Method | Input Type | Performance | Use Case |
|---|---|---|---|
| clone + foreach | Object | Slower | Object inheritance |
| array_fill_keys() | Array | Faster | Template creation |
Conclusion
Both methods effectively inherit the property structure while nullifying values. Use clone with foreach for objects and array_fill_keys() for arrays when creating object templates.
Advertisements
