虽然PHP中的类不需要显式扩展 stdClass, ,我想知道这样做是否有某种最佳实践或好处。

我应该延长吗 stdClass 声明类时?

有关参考,请参阅 PHP中的stdClass是什么?PHP的:对象,转换为对象.

有帮助吗?

解决方案

StdClass 是空的,因此你没有任何好处扩展它。

你只是在浪费时间 extend 在你的 __CLASS__˙.

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

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [0] {
  }
}

延长的唯一理由 stdClass 是为了满足针对这个类的typehint-但是,永远不应该使用这样的typehint,因为这是一个有争议的问题。

其他提示

非也。           

扩展stdClass有一个有趣的用途:(st object instanceof stdClass)将返回true,比is_object($object)快3倍。我们说的是1 第二个区别,虽然不幸的是,除非你在整个项目中把它作为一个严格的政策,否则它很容易变得不连贯,因此比帮助更令人困惑。事实上,我很失望地得知PHP类默认情况下不会扩展stdClass。我会理解的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top