I know it can be done using third-party packages, but is there any technical reason PHP can't serialize closures by itself?
-
3See comments of this answer: https://stackoverflow.com/a/13734344/1427345 – Jacob Mulquin Dec 29 '21 at 05:07
1 Answers
Because it isn't data. Serializing is a term that really only applies to data.
Serializing a closure is like "smoking an idea", an idea isn't a physical thing you can light on fire so you cannot smoke it. Now, you could write down an idea on a piece of paper, and then light that on fire and smoke it; but really that still wouldn't be the act of smoking the idea.
Likewise, you could take the lines of code that was used to create the closure, and you could serialize all the variables related to it, and describe its context somehow (such as what file it used to be in and such), and then serialize all of that. But again, that wouldn't really be serializing the closure.
Basically there is a certain type of problem, that people commonly run into in regards to data, and they often end up solving that problem using serialization. Now when those same people run into the same kind of problem but in regards to closure(s) instead of data; they may end up searching for "how to serialize a closure", not having given any thought to the underlying realities.
Libraries that have a solution for the initial problem, may advertise themselves as offering closure serialization, because that makes sense from a SEO/advertising point of view; but it is not an accurate description of what their code actually does.

- 2,452
- 1
- 6
- 10