자료구조 Ds\Hashable::hash
(PECL ds >= 1.0.0)
Ds\Hashable::hash — 해시 값으로 사용할 스칼라 값을 반환합니다.
설명
abstract public Ds\Hashable::hash(): mixed
개체의 해시 값으로 사용할 스칼라 값을 반환합니다.
해시 값이 같음을 정의하지는 않지만 Ds\Hashable::equals()에 따라 동일한 모든 개체는 동일한 해시 값을 가져야 합니다. 동일한 객체의 해시 값은 고유할 필요가 없습니다. 예를 들어 모든 객체에 대해 true
를 반환하면 아무 것도 깨지지 않습니다. 유일한 의미는 해시 테이블이 연결된 목록으로 바뀌는 것입니다. 같은 양동이. 따라서 ID 또는 이메일 주소와 같은 좋은 해시 값을 선택하는 것이 매우 중요합니다.
이 메서드를 사용하면 Ds\Map 및 Ds\Set 같은 구조 또는 이 인터페이스를 사용하는 다른 조회 구조에서 개체를 키로 사용할 수 있습니다.
주의 공용 속성과 같이 개체 내에서 변경될 수 있는 값을 선택하지 마십시오. 해시가 변경되었기 때문에 해시 테이블 조회가 실패합니다.
주의 동일한 모든 개체는 동일한 해시 값을 가져야 합니다.
매개변수
이 함수에는 매개변수가 없습니다.
반환 값
이 개체의 해시 값으로 사용할 스칼라 값입니다.
Examples
예제 #1 Ds\Hashable::hash() 예제
<?php
class HashableObject implements \Ds\Hashable
{
private $name;
private $email;
public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
/**
* Should return the same value for all equal objects, but doesn't have to
* be unique. This value will not be used to determine equality.
*/
public function hash()
{
return $this->email;
}
/**
* This determines equality, usually during a hash table lookup to determine
* if the bucket's key matches the lookup key. The hash has to be equal if
* the objects are equal, otherwise this determination wouldn't be reached.
*/
public function equals($obj): bool
{
return $this->name === $obj->name
&& $this->email === $obj->email;
}
}
?>