TOMP TOMP - 19 days ago 6
PHP Question

php array converting child class with sha1

I have the following piece of code (example for the problem):

class A {
public $x;
public $y;
public function __construct($x, $y) {
$this->x = sha1($x);
$this->y = $y;
}
public function __clone() {
return new A($this->x, $this->y);
}
}

class B extends A {

public $z;
public function __construct($z, $parent_obj) {
$this->z = $z;
parent::__construct($parent_obj->x, $parent_obj->y);
}
public function doSomeThing() {
$parent_a_array = (array) parent::__clone();
$child_a_array = array_diff_assoc((array) $this, $parent_a_array);
echo "Parent Array Printing :<br/>";
foreach ($parent_a_array as $key => $value) {
echo "Key: $key; Value: $value\n".'<br/>';
}
echo "Child Array Printing: <br/>";
foreach ($child_a_array as $key => $value) {
echo "Key: $key; Value: $value\n".'<br/>';
}


}
}

$t = new B('C', new A("A", "B"));
$t->doSomeThing();


I get a little bit weird output, i expect to have x,y printable only in parent, while z printable only on child, but the output is

Parent Array Printing :
Key: x; Value: 726c6aeb8252ad589562fe2c7409d50c90a058aa
Key: y; Value: B
Child Array Printing:
Key: z; Value: C
Key: x; Value: bd605412133b28b10c5fa7a45fce29df67c18bd7


When I remove the call to sha1 function in class A contructor, the output seems to be fine.

Parent Array Printing :
Key: x; Value: A
Key: y; Value: B
Child Array Printing:
Key: z; Value: C


I'll be grateful if any one knows a solution for this problem.

Answer

You are hashing x twice when you are cloning it, hence the x in the instance of B has a different value than the one in the clone of its parent (A).

$this->x = sha1($x) then in the clone you have new A($this->x, $this->y) which in fact is new A(sha1(x), $this->y). So you end up with this

t = {
   x: sha1('A'),
   y: 'B',
   z: 'C'
}
clone_of_t = {
   x: sha1(sha1('A')),
   y: 'B'
}