Nasıl PHP iki sınıfını birleştirmek için?

2 Cevap php

Final class sınıfında hem de tüm üye değişkenler / yöntemler var ki

Gitmek için kolay bir yol var mı?

2 Cevap

Sen içeren bir sınıfta hem sınıfları saklanması ve bu özel değişkenler için belirleyiciler / alıcılar olarak ilgili arayüzü (vermelidir

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

Araştırma (google): "miras üzerinden kompozisyon"

Dipnot: non-yaratıcı değişken isimleri için üzgünüm ..

# 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;
    }
}

Sen ilk yöntem düşünmelisiniz sanki burada array_combine() . Then consider the second method as if it where the object counterpart for array_merge() nesne muadili.