The following code comes from Google's recaptcha library. Instead of using stdClass, they used a separate class. I understand why this would be helpful if they were pre-setting properties (either to a given value or even to NULL), but don't see why they did so in this case. Is there any value to doing it as they did, or would stdClass be more appropriate?
class ReCaptchaResponse {
var $is_valid;
var $error;
}
$recaptcha_response = new ReCaptchaResponse();
$recaptcha_response->is_valid = false;
$recaptcha_response->error = 'incorrect-captcha-sol';
This is partly a matter of opinion, but personally I have never used stdClass
, and I've never understood the point of doing so.
The purpose of an object is to encapsulate data and behaviour, whether that's by adding public and private methods to the object, using inheritance and polymorphism to structure your project, or just having a well-defined named type.
In some languages, e.g. JavaScript, an object is useful as a general-purpose key-value store, even if properties are added completely ad hoc; in PHP, that role can simply and effectively be filled by an associative array.
Some people will use stdClass
objects as key-value stores, but they lose the use of all the functions around arrays by doing so. As ZubaiR points out above an object will be passed/assigned as a kind of pointer (not the same as passing a variable by reference) rather than being copied as necessary, so will behave differently, but if you're not deliberately using the "encapsulation" aspect of OOP (in which case you would probably create a class), it's hard to say if this is a good thing or just a chance for confusion.
In other languages, such as C, there is a way of defining custom "struct" types, with pre-defined named members. PHP has no such type, but a simple methodless class like the one you show is pretty close.
Another advantage in other languages that doesn't apply in PHP is that the base class for objects could have some functionality, or even - as in JavaScript or Ruby - allow you to add some functionality. In PHP, stdClass
is completely inert and cannot be edited, and as pointed out elsewhere is not in fact used as a base class for other objects; it's only "magic" ability is to be the target class when something is cast or "juggled" to be of type object
.
The immediate benefits of using a named class include:
instanceOf
)