This is possible using the reflection API, but might be quite slow itself:
- Create a ReflectionFunction object
- Call
getFileName()
and load the source code, e.g. with file_get_contents()
or file()
(which splits the file into an array of lines)
- Call
getStartLine()
, and getEndLine()
, and extract those lines from the source file
- That will give you the source code for the function, which you can then hash to form your cache key
There is also a library called BetterReflection which loads source code from a file and parses it without executing it, and can return re-constructed source code (i.e. functionally identical, but not laid out as in the original). This might be useful to avoid formatting changes causing the hash to change, but will be even slower.
If you have a large number of functions to hash, you will probably want to make a build script which loads a whole class or file, and loops over it generating a hash of each function. You can then store those hashes in a look-up table (saved on disk as a PHP or JSON array) which the caching code can use to look up by function name.
It's worth considering some alternative approaches which are likely to be simpler and more efficient:
- Key the cache on the version of the application. This will probably have more false positives (unnecessary repeated work) but no false negatives (caches kept too long).
- Manually increment a version within the function. This is more work to maintain, but if done correctly eliminates both false negatives and false positives.