Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real and steady hash of object

Tags:

oop

php

I need to clearly identify an object and store it's identification within my DB. Afterwards i need this ID to restore this object back.

I tried using "spl_object_hash()" (http://php.net/manual/en/function.spl-object-hash.php) but this function returns another value each time I reload the page.

For testing, this objects is steady and stays the same and completely unchanged. Never the less "spl_object_hash()" returns different results time and time again I do a reload.

$foo = new stdClass();
print_r(spl_object_hash($foo));

-> another hash every time I hit refresh

I need a way to creates a hash depending on the complete object. This hash should not change as long as the object does not.

I don't want to implement an own method (as long as there is no other possibility for solving my problem) for this, for I need a quick, easy and uniform way to identify my objects.

Further more I don't want to use Sessions for this purpose.

So what can I do to workaround this Problem?

Thanks ahead & friendly regards!

like image 446
serjoscha Avatar asked Jan 20 '14 14:01

serjoscha


2 Answers

You can use serialize call (with overriden __sleep() magic call) to serialize the object, to get a unique hash :

$hash = md5(serialize($myObject));

Plus in objects where you store some extra data (like PDO handler, file handle) you can overwrite __sleep() and __wakeup() methods to get/set only object data, for example code from http://www.php.net/manual/en/language.oop5.magic.php#object.sleep

<?php
class Connection
{
    protected $link;
    private $dsn, $username, $password;

    public function __construct($dsn, $username, $password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->connect();
    }

    private function connect()
    {
        $this->link = new PDO($this->dsn, $this->username, $this->password);
    }

    public function __sleep()
    {
        return array('dsn', 'username', 'password');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}?>

this should give you a good hash of object, and even better, you can configure which fields you want to use to create hash.

like image 62
PolishDeveloper Avatar answered Sep 30 '22 01:09

PolishDeveloper


You can always do this :

function object_hash($object, $algorithm = 'md5') {
    $serialized_object = serialize($foo);

    return hash($algorithm, $serialized_object);
}

$foo = new stdClass();
print_r(object_hash($foo));
like image 33
Dysosmus Avatar answered Sep 30 '22 03:09

Dysosmus