Yes. All code accessing the shared resource (in this case $this->fileName
) simply needs to agree to lock something, not necessarily the shared resource.
For example (pseudo-code):
$lock = flock('/tmp/lockfile');
file_put_contents('/etc/foo.ini', 'whatever');
funlock($lock);
Notice the thing I'm locking is not the same thing I'm overwriting.
However, traditionally flock
is applied to the file handle for the shared file, simply because it's easier than opening another handle just for a lock file (and saves the memory allocation of said opening). There's no requirement for that, though, just programmer ease.
In general, flock
is a means to provide a cooperative, advisory, read-write locking mechanism on top of the file system: it doesn't actually do anything to the thing being locked.