Question

While it is not required for a class in PHP to explicitly extend stdClass, I was wondering if there is some kind of best practice or benefit in doing so.

Should I extend stdClass when declaring a class?

For reference, see What is stdClass in PHP? and PHP: Objects, Converting to object.

Was it helpful?

Solution

StdClass is empty and therefore you don't have any benefit in extending it.

You are just wasting extend in your __CLASS__˙.

php --rc StdClass
Class [ <internal:Core> class stdClass ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [0] {
  }
}

The only reason to extend stdClass is to satisfy a typehint against this class - however, such a typehint should never be used, as such this is a moot point.

OTHER TIPS

No           

There's one fun use to extend stdClass: ($object instanceof stdClass) will return true and is 3x faster than is_object($object). We're talking a 1 microsecond difference, though and unfortunately, unless you make it a strict policy throughout the project, it can easily become incoherent and thus more confusing than helping. In fact, I'm disappointed to learn that PHP classes don't extend stdClass by default. Would have made sense to me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top