0

私は2つの非常によく似たクラスを持っています。クラスAとクラスBとしましょう。

+---------------+      +---------------+
| Class A       |      | Class B       |
|---------------|      |---------------|
|   Name        |      |   Name        |
|   ZIP         |      |   ZIP         |
|   TelPhone    |      |   TelPhone    |
|               |      |   MobilePhone |
+---------------+      +---------------+

すべての共通属性の値でそれらを比較したいと思います。

これは私が試した方法ですが、すべての属性(3つ以上の属性を取得)に対して行うのはやり過ぎのように見えます:

$differences = array();

if($classA->getName() != $classB->getName()) {
    array_push(
        $differences, 
            array('name' => array(
                'classA' => $classA->getName(),
                'classB' => $classB->getName()
            )
    ));
}
// and the same code for every attribute....

ここで最善のアプローチは何ですか?

手作業に加えて、クラスが変更されても自動的に更新されません。たとえば、クラス A が MobilePhone 属性も取得するとします。

ポリモーフィズムを行う必要があるとは言わないでください。明確にするための例にすぎません。

その違いに興味があるので、属性だけでなく、属性内の値そのものも。

ありがとう

4

1 に答える 1

0

それは最もセクシーなものではありません(ゲッターへの部分文字列のため..、しかし、私はプロパティに行くことができません、私はsymだと思いますが、私はそれを手に入れました:

// getting an array with all getter methods of a class
private function getGettersOf($object) {

        $methodArray = array();

        $reflection = new ReflectionClass($object);
        $methods = $reflection->getMethods();

        foreach ($methods as $method) {
            // nur getter
            if(strtolower(substr($method->getName(), 0, 3)) == "get") {
                array_push($methodArray, $method->getName());
            }
        }
        return $methodArray;
    }


// getting an array with all differences
public function getDifferences($classA, $classB) {
        // get list of attributes (getter methods) in commond
        $classAMethods = $this->getGettersOf($classA);
        $classBMethods = $this->getGettersOf($classB);

        $intersection = array_intersect($classAMethods, $classBMethods);

        $differences = array();

        // iterate over all methods and check for the values of the reflected methods
        foreach($intersection as $method) {
            $refMethodClassB = new ReflectionMethod($classB, $method);
            $refMethodClassA = new ReflectionMethod($classA, $method);

            if($refMethodClassB->invoke($classB) != $refMethodClassA->invoke($classA)) {
                array_push(
                    $differences,
                    array($method => array(
                        'classA' => $refMethodClassA->invoke($classA),
                        'classB' => $refMethodClassB->invoke($classB)
                    )
                ));
            }

        }

        return $differences;
    }

George Marques のコメントに感謝します。

于 2013-09-16T12:00:38.940 に答える