2010-03-03 78 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()的对象所在的位置。