The algorithm used and its cost are embedded in the password hash. It's the first couple of letters:
$2y$10$abcdefg...123456789...
| | | |
| | | +- the password hash
| | +- the salt
| +- the cost parameter
+- the algorithm type
(Also see https://stackoverflow.com/a/16736254/476)
As such, when verifying the password, password_verify
knows what algorithm to use.
The use of checking whether the password needs rehashing is to confirm whether the algorithm and cost factor embedded in the hash are still the same as the ones you would like to use. If they are not the same, you should rehash the password with the new configuration.
The typical use is that over time, you will increase the cost factor as hardware gets faster and can handle hashing with larger costs. That does not suddenly invalidate your old passwords, those will still be confirmed using the old settings embedded in the hash. However, since you happen to have the plaintext password at hand at the time of verification, you should use that opportunity to update the hash with the newer settings.