这样最后一个类在类
中都有所有成员变量/方法有简单的方法吗?
答案 0 :(得分:11)
您应该将这两个类封装在一个包含的类中,并提供相关的接口(例如私有变量的setter / getters
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);
}
}
研究(谷歌):“继承的构成”
脚注:抱歉非创意变量名称..
答案 1 :(得分:0)
您是要求在运行时或编程时执行此操作吗?
我将假设运行时,在这种情况下使用类inheritance有什么问题?
创建一个继承自要合并的类的新类。
答案 2 :(得分: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()
对象的对应位置。