2012-10-18 70 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