• PHP Video Tutorials

PHP - Ds\Hashable::hash() Function



Ds\Hashable::hash() function can return a scalar value to be used as the hash value.

Syntax

public abstract mixed Ds\Hashable::hash( void )

Ds\Hashable::hash() function can return a scalar value to be used as the hash value of objects.

While hash value doesn't define equality, all objects that are equal according to Ds\Hashable:: equals() function must have the same hash value. The hash values of equal objects do not have to unique. For instance, we can just return true for all objects and nothing can break. The only implication is that hash tables then turn into linked lists because all our objects can be hashed to the same bucket. Therefore, very important that we can pick a good hash value such as ID or email address.

Ds\Hashable::hash() function can allow objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Example

<?php
   class HashableObject implements \Ds\Hashable {
      private $name;
      private $email;

      public function __construct($name, $email) {
         $this->name  = $name;
         $this->email = $email;
      }
      public function hash() {
         return $this->email;
      }
      public function equals($obj): bool {
         return $this->name === $obj->name && $this->email === $obj->email;
      }
   }
?>
php_function_reference.htm
Advertisements