为什么此文件锁定功能失败?

I wrote the following code for a generic function to acquire a file-based lock in a class in a php script that is run very often.

private static $flocks = [];
public static function getLock($fname) {

    $fp = null;

    try {
        $fp = fopen($fname . '.lock', 'w');
        if ($fp === false) return false;
    } catch (\Exception $e) {
        return false;
    }

    try {
        if (!flock($fp, LOCK_EX | LOCK_NB)) return false;
    } catch (\Exception $e) {
        return false;
    }

    self::$flocks[$fname] =& $fp;
    return true;
}

Afterwards I tried it out with this script:

        $yy = self::getLock('snorlax');
        if ($yy) {
            echo("WAITING...
");
            sleep(10);
            echo("DONE");
        } else {
            echo("UNABLE TO GET LOCK");
        }

My problem here is that it always gets the lock. This is a var_dump of the static array at the end of the test script...

array(1) {
  ["snorlax"]=>
  resource(659) of type (stream)
}

I am now doubting that an array is not the correct way to keep the filepointer active / in scope. Please advise!

I was thinking about variable variables but that sounds like a big mess.

The file lock is working, but I made the wrong assumption that it would immediately fail. Instead the script is waiting for the lock to be released. So this was the reason the script always got the lock.