2

从下面的代码中,有没有人知道从 B 中定义的方法将 $parent->foo 和 $parent->foo1 的值分别放入 $child->bar 和 $child->bar1 的方法?

我可以用 $child->bar=$parent->foo 和 $child->bar1=$parent->foo1 在对象之外复制值,但感觉孩子(甚至是父母)中可能有一个简单的方法就此而言)对于这种情况。我的父对象正在从 html 输入框中获取 foo 的值。

Class A 
{
    public $foo="someText";
    public $foo1="someOtherText";
}

Class B extends A 
{
    public $bar;
    public $bar1;

    //theoretical function Id like to use
    public copyParentcontents() 
    {

    }
}

$parent = new A();
$child = new B();
4

2 回答 2

1
Class B extends A {

public $bar;
public $bar1;

//theoretical function Id like to use
public copyParentcontents($parent) {
    if(get_class($parent)=="A"){
        $this->$bar = $parent->foo;
        $this->$bar1 = $parent->foo1;
    }else{
    //You could throw an exception here
    }
}

}

接着:

$parent= new A; $child= new B; 
$parent->foo = "modifiedText";
$child->copyParentcontents($parent);

也许这就是你需要的?

于 2012-10-18T19:11:50.737 回答
0

在您的示例中,$child将从以下位置继承类参数$parent

echo $child->foo; // prints "someText";
于 2012-10-18T19:12:12.067 回答