2012-10-18 135 views
2

从下面的代码中,没有人知道如何将$ parent-> foo和$ parent-> foo1的值放入$ child-> bar和$ child-> bar1分别从B中定义的方法?PHP将父级属性值复制到子级属性值

我可以用$ 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(); 

回答

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); 

也许这就是你需要什么?

+0

这看起来像它会做的伎俩!谢谢! – JoshL

0

在你的榜样,$child将从$parent继承类参数:

echo $child->foo; // prints "someText"; 
+0

你是对的,但我相信他正在改变父实例的属性值:“我的父对象从html输入框中获取foo的值。” –

+0

是的,我也是这么读的,他的示例代码有点让人误解:) –

+0

对不起,误导性的代码!我对面向对象很陌生,并试图混淆所有事情。 '$ child'是'$ foo'值的最后位置,并且是我连接到我的mysql服务器的地方。 '$ parent'是我得到用户输入并进行错误检查和验证的地方。有没有更好的和/或更有效的方式来处理我试图做的事情? – JoshL