PHP-以某种方式散列对象distint具有相同字段值的对象具有相同的散列 [英] PHP - hash objects in a way distint object with same fields values have same hash

查看:73
本文介绍了PHP-以某种方式散列对象distint具有相同字段值的对象具有相同的散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种为PHP对象生成某种哈希的方法(通用解决方案,如果可能的话,可与所有分类的,内置的和自定义的一起使用).

I am looking for a way to generate some kind of hash for PHP object (generic solution, working with all classed, built-in and custom, if possible).

SplObjectStorage :: getHash不是我想要的,因为它将为给定类的每个实例生成不同的哈希.为了说明问题,让我们考虑简单的类:

SplObjectStorage::getHash is not what I'm looking for, as it will generate different hash for every instance of given class. To picture the problem, let's consider simple class:

class A() {
public $field; //public only for simplicity
}

和该类的2个实例:

$a = new A(); $a->field = 'b';
$b = new A(); $b->field = 'b';

我尝试过的每个内置函数都会为这些对象返回不同的哈希值,而我想使用属性 f($ a)== f($ b)=>$ a == $ b .

Every built-in function I've tried will return different hashes for these objects, while I'd like to have some function f($x) with property f($a) == f($b) => $a == $b.

我知道我可以编写一个函数来递归地遍历所有对象的属性,直到找到可以转换为字符串的属性,然后以奇特的方式将这些字符串连接起来并进行哈希处理,但是这种解决方案的性能会很糟糕.

I am aware I could write a function traversing all object's properties recursively until I find a property that can be casted to string, concatenate this strings in fancy way and hash, but the performance of such solution would be awful.

是否有一种有效的方法来做到这一点?

Is there an efficient way to do this?

推荐答案

假设我理解正确,可以先序列化对象,然后md5序列化的对象.由于如果所有属性都相同,则序列化会创建相同的字符串,因此每次都应获得相同的哈希值.除非您的对象具有某种时间戳属性.示例:

Assuming I understand you correctly, you could serialize the objects then md5 the serialized object. Since the serialization creates the same string if all properties are the same, you should get the same hash every time. Unless your object has some kind of timestamp property. Example:

class A {
    public $field;
}
$a = new A;
$b = new A;
$a->field = 'test';
$b->field = 'test';
echo md5(serialize($a)) . "\n";
echo md5(serialize($b)) . "\n";

输出:

0a0a68371e44a55cfdeabb04e61b70f7
0a0a68371e44a55cfdeabb04e61b70f7

您的输出结果有所不同,因为php内存中的对象存储有每个实例的编号ID:

Yours are coming out differently because the object in php memory is stored with a numbered id of each instantiation:

object(A)#1 (1) {...
object(A)#2 (1) {...

这篇关于PHP-以某种方式散列对象distint具有相同字段值的对象具有相同的散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆