Shortest way to convert all PHP types to string
P粉369196603
2023-09-05 15:34:44
<p>I'm writing a general system that I hope will one day be applicable to fields such as medicine (i.e. it will be "scientific"). </p>
<p>I think the best way is to represent all the data in php with strings (true will be "true", false will be "false" and so on). The reason for this is that in php any value has a unique string representation (such as the php code itself). </p>
<p>I am posting this question to speed up the design process of this program. </p>
<p>Some values are easily converted to strings: numbers, booleans, etc. </p>
<p>Some are not easy: objects, arrays, resources. </p>
<p>I think the format for transferring objects and arrays is basically json, but I'm not sure if it matches exactly. This is better than what I currently have (nothing), but at least at some point I'd like to refine it to a point. </p>
<p>Any ideas? </p>
This is indeed an ambitious goal; so ambitious that it would be foolish to try.
Now, you probably don't really mean "can do anything for anyone", but the fact that you're trying to express that without setting any limits is relevant to your question. This makes it unnecessarily difficult for you to find a serialization format.
For example, you mentioned Resources, which PHP uses for things like database connections, opening file handles, etc. They are ephemeral pointers to something that live for a while and then disappear, and serializing them is not only unsupported in PHP, but also makes almost no sense.
Instead of trying to cover "everything", you need to consider what types of data you actually need to process. Maybe you'll mainly use classes defined within the system, so you can define any format you want to represent them. Maybe you want to process an arbitrary collection of key-value pairs, in the form of a PHP array. You might want to leave room for future extensions, but that's just about flexibility of the format, not a concrete answer right now.
From there, you can look for the property you want and shop around:
Obviously, the list is endless...