1

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';
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • possible duplicate of [When should I use stdClass and when should I use an array in php oo code?](http://stackoverflow.com/questions/3193765/when-should-i-use-stdclass-and-when-should-i-use-an-array-in-php-oo-code) – IMSoP Jan 25 '14 at 17:46
  • Another related question, dealing more with actual named classes, but with some comments about `stdClass` in the answers: http://stackoverflow.com/q/2056931/157957 – IMSoP Jan 25 '14 at 17:59
  • @IMSoP. I don't think it is a duplicate. I read that question prior to posting mine, and it questions whether objects or arrays should be used. I am asking whether the predefined `stdClass` should be used. – user1032531 Jan 25 '14 at 18:02
  • Good point; I think all three questions touch on some of the same issues without actually being the same. http://stackoverflow.com/q/931407/157957 is also related, but not very informative. – IMSoP Jan 25 '14 at 18:22

5 Answers5

3

Is there any value to doing it as they did, or would stdClass be more appropriate

  1. ReCapchaResponse is more user friendly than stdClass
  2. Adds possibility to extend the class in future without modifying other sections.

Why use stdClass at all ? Can't we use arrays for all the same cases ?

If you want to pass a data from one function to another and also modify the data then you can use stdClass. You can do the same with associative array but then you have a possibility of an error if you miss call by reference.

$a = array();
function test1(&$a) {
    $a['key'] = 1234;
}
test($a);

function test2($a) { // possible error
    $a['key'] = 1234;
}
test2($a);

$a = new stdClass();
function test3($a) {
    $a->key = 1234;
}
test3($a);

But this type of structure is highly unlikely in practical scenario.

ZubaiR
  • 607
  • 4
  • 7
  • +1 for mentioning the edit-in-place aspect, which hadn't occurred to me. Although arguably if you're using `stdClass` like a "struct", it's actually *less* intuitive to have that behaviour, which really makes more sense when you are using object methods that have side-effects. – IMSoP Jan 25 '14 at 17:48
  • It is hard to argue about usability of stdClass in php, since we can do things in other ways too. Personally I think use if stdClass is less intuitive :P – ZubaiR Jan 25 '14 at 17:56
  • why there will be error in function test2($a) { // possible error $a['key'] = 1234; } – Stack user Oct 22 '19 at 05:45
2

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:

  • the PHP engine, and tools such as IDEs and code sniffers, know which properties "should" exist, and can warn you if you set invalid ones, e.g. through a spelling mistake
  • you can check if a particular value passed is the right type of object (using instanceOf) rather than
  • you can easily expand the object later to have extra functionality, or make it part of an inheritance hierarchy, etc
Community
  • 1
  • 1
IMSoP
  • 89,526
  • 13
  • 117
  • 169
0

For example, think about this class as interface and extendability in the future. ReCaptchaResponse is also stdClass.

You should ask author about his idea.

Krzysztek
  • 11
  • 3
0

ReCaptchaResponse is nicer to read and more comprehensible than stdClass.

But programmatically it's the same.

  • Then do you promote never using `stdClass`? – user1032531 Jan 25 '14 at 17:35
  • In some cases it is more convenient to use `stdClass`. For example when wrapping some variables within a object in order to `json_encode()` them. But comprehensive OOP Structures should have 'meaningful' class names. –  Jan 25 '14 at 17:35
  • @Rotherford Would wrapping them in an associative array not have the same effect, and be even simpler to declare? – IMSoP Jan 25 '14 at 17:38
  • basically there is no difference. http://stackoverflow.com/questions/3193765/when-should-i-use-stdclass-and-when-should-i-use-an-array-in-php-oo-code –  Jan 25 '14 at 17:41
  • @Rotherford That looks like a near-duplicate of this question actually. But what I meant was that initialising an array like `$x = ['foo' => $foo, 'bar' => $bar]` is a lot simpler than initialising an object like `$x = new stdClass; $x->foo = $foo; $x->bar = $bar;` - and passing `(object)['foo' => $foo, 'bar' => $bar]` to `json_encode` would be completely pointless. – IMSoP Jan 25 '14 at 17:44
  • Yes. `json_encode`supports both object/array. no casting required. eventually It is up to you. If you like quoting property names... –  Jan 25 '14 at 17:50
0

I personally would never, ever write any new code that instantiates an instance of stdClass.

By creating your own classes, even if you don't add any functionality at all, you're able to explicitly say what that object represents, eg a result returned by an API client, and someone consuming that API can typehint that class to ensure objects of that type are passed through.

Also, if you're using an object as a simple container for data, it often makes sense to implement ArrayAccess, Countable and either Iterator or IteratorAggregate - that way you can loop through it or access it like an array, which is tremendously useful.

Matthew Daly
  • 9,212
  • 2
  • 42
  • 83