gpt4 book ai didi

php - 在将数据保留在基类中的同时复制 PHP 类的实例?

转载 作者:搜寻专家 更新时间:2023-10-31 21:16:29 24 4
gpt4 key购买 nike

我有以下三个类:

class a
{ public $test; }

class b extends a { }
class c extends a
{
function return_instance_of_b() { }
}

如您所见,bc 类都派生自a。在 creturn_instance_of_b() 函数中,我想返回类 b 的一个实例。基本上 return new b(); 有一个额外的限制:

我需要将基类 (a) 中的数据复制到返回的 b 实例中。我该怎么做呢?也许是 clone 关键字的某种变体?

最佳答案

您可以使用 get_class_vars函数检索要复制的变量的名称,然后循环复制它们。

定义的变量是 protected ,因此它们在其范围内对 get_class_vars 可见(因为 c 扩展了 a),但不能在类外直接访问。您可以将它们更改为 public,但 private 将从 get_class_vars 中隐藏这些变量。

<?php
class a
{
protected $var1;
protected $var2;
}

class b extends a
{
}

class c extends a
{
function __construct()
{
$this->var1 = "Test";
$this->var2 = "Data";
}

function return_instance_of_b()
{
$b = new b();
// Note: get_class_vars is scope-dependant - It will not return variables not visible in the current scope
foreach( get_class_vars( 'a') as $name => $value) {
$b->$name = $this->$name;
}
return $b;
}
}

$c = new c();
$b = $c->return_instance_of_b();
var_dump( $b); // $b->var1 = "Test", $b->var2 = "Data

关于php - 在将数据保留在基类中的同时复制 PHP 类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7509953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com