2010-03-03 83 views

回答

9

您應該封裝中含有類兩個類別,並提供了相應的接口(如私有變量

class YourFirstClass { 
    public $variable; 
    private $_variable2; 
    public function setVariable2($a) { 
     $this->_variable2 = $a; 
    } 
} 

class YourSecondClass { 
    public $variable; 
    private $_variable2; 
    public function setVariable2($a) { 
     $this->_variable2 = $a; 
    } 
} 

class ContaingClass { 
    private $_first; 
    private $_second; 
    public function __construct(YourFirstClass $first, YourSecondClass $second) { 
     $this->_first = $first; 
     $this->_second = $second; 
    } 
    public function doSomething($aa) { 
     $this->_first->setVariable2($aa); 
    } 
} 

研究(谷歌)制定者/吸氣:「組成了繼承」

腳註:對於非創造性的變量名稱感到抱歉。

+0

不,我需要運行它。 – user198729 2010-03-03 21:00:30

+6

@ user198729:考慮到你的「在運行時」的要求,你真的想要合併兩個*類*,還是你的意思是說兩個*對象*? – 2010-03-03 21:07:35

0

您是要求在運行時或編程時執行此操作嗎?
我將假定運行時,在這種情況下使用c1有什麼問題屁股inheritance
創建一個從您想要合併的兩個繼承的新類。

+2

不下調,但PHP不支持(afaik)多重繼承。 – ChristopheD 2010-03-03 20:56:01

+1

這不會讓您訪問繼承類的私有成員。 – tloach 2010-03-03 20:56:15

+2

是的,對不起,PHP不支持多重繼承。但是,通過堆疊類來從一個或另一個繼承,可以模擬多重繼承。 私人會員不會被繼承,是的。但是,如果這是一個問題,將保護措施轉變爲公衆並不是特別困難(我們不會開始討論是否真的需要私人保護)。 – 2010-03-03 21:21:57

0
# Merge only properties that are shared between the two classes into this object. 
public function conservativeMerge($objectToMerge) 
{ 
    # Makes sure the argument is an object. 
    if(!is_object($objectToMerge)) 
     return FALSE; 

    # Used $this to make sure that only known properties in this class are shared. 
    # Note: You can only iterate over an object as of 5.3.0 or greater. 
    foreach ($this as $property => $value) 
    { 
     # Makes sure that the mering object has this property. 
     if (isset($objectToMerge->$property)) 
     { 
      $objectToMerge->$property = $value; 
     } 
    } 
} 


# Merge all $objectToMerge's properties to this object. 
public function liberalMerge($objectToMerge) 
{ 
    # Makes sure the argument is an object. 
    if(!is_object($objectToMerge)) 
     return FALSE; 

    # Note: You can only iterate over an object as of 5.3.0 or greater. 
    foreach ($objectToMerge as $property => $value) 
    { 
     $objectToMerge->$property = $value; 
    } 
} 

你首先應該考慮的方法,就好像它在那裏的array_combine()的對象對應。然後考慮第二種方法,就好像它在array_merge()的對象所在的位置。