PHP 继承非类对象的属性?
为此,使用 clone 以及将属性名称设置为 null。
示例
PHP 代码如下所示
<!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>
输出
将产生以下输出
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 }
广告