Search code examples
phptypesstructuretype-safety

Emulating a value type structure class in PHP


Is there any way to emulate a structure class in PHP? ie a class which passes by value and not by reference, so it can still be type hinted...

And if so, what different techniques could be used? What's the best technique?

If this is possible you could obviously create a fully type safe layer for PHP, are there such layers? Has anyone had any experience with this?


Solution

  • Objects are always passed by reference. The only way to make them pass as a copy is to explicitly use the clone keyword (yes, everywhere).

    My recommendation would be to use an array, which are value types and thus always copied. Since you can use it as an associative array (eg string -> value), it might as well be an object. The downside is, of course, you can't use methods (but that's like a struct so you may be happy with this). There is no way to enforce type safety, however.

    But with all your requirements it sounds like PHP isn't your kind of language, to be honest.