php 用 sha1 转换子数组 class
php array converting child class with sha1
我有以下代码(问题示例):
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();
我得到了一些奇怪的输出,我希望 x,y 只能在父级上打印,而 z 只能在子级上打印,但输出是
Parent Array Printing :
Key: x; Value: 726c6aeb8252ad589562fe2c7409d50c90a058aa
Key: y; Value: B
Child Array Printing:
Key: z; Value: C
Key: x; Value: bd605412133b28b10c5fa7a45fce29df67c18bd7
当我在 class 构造函数中删除对 sha1 函数的调用时,输出似乎没问题。
Parent Array Printing :
Key: x; Value: A
Key: y; Value: B
Child Array Printing:
Key: z; Value: C
如果有人知道这个问题的解决方案,我将不胜感激。
克隆 x 时,您对它进行了两次哈希处理,因此 B 实例中的 x 与其父实例 (A) 中的 x 具有不同的值。
$this->x = sha1($x)
然后在克隆中你有 new A($this->x, $this->y)
实际上是 new A(sha1(x), $this->y)
。所以你最终得到这个
t = {
x: sha1('A'),
y: 'B',
z: 'C'
}
clone_of_t = {
x: sha1(sha1('A')),
y: 'B'
}
我有以下代码(问题示例):
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();
我得到了一些奇怪的输出,我希望 x,y 只能在父级上打印,而 z 只能在子级上打印,但输出是
Parent Array Printing :
Key: x; Value: 726c6aeb8252ad589562fe2c7409d50c90a058aa
Key: y; Value: B
Child Array Printing:
Key: z; Value: C
Key: x; Value: bd605412133b28b10c5fa7a45fce29df67c18bd7
当我在 class 构造函数中删除对 sha1 函数的调用时,输出似乎没问题。
Parent Array Printing :
Key: x; Value: A
Key: y; Value: B
Child Array Printing:
Key: z; Value: C
如果有人知道这个问题的解决方案,我将不胜感激。
克隆 x 时,您对它进行了两次哈希处理,因此 B 实例中的 x 与其父实例 (A) 中的 x 具有不同的值。
$this->x = sha1($x)
然后在克隆中你有 new A($this->x, $this->y)
实际上是 new A(sha1(x), $this->y)
。所以你最终得到这个
t = {
x: sha1('A'),
y: 'B',
z: 'C'
}
clone_of_t = {
x: sha1(sha1('A')),
y: 'B'
}