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.
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
The stdClass is a generic empty class used to cast the other type values to the object. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. The stdClass is not the base class for objects in PHP.
Creating stdClass Object <? php $obj= new stdClass(); $obj->name= 'W3schools'; $obj->extension= 'In'; var_dump($object); ?> Whenever you need a generic object instance in your program, you can use stdClass because when you cast any other type to an object, you will get an instance of stdClass.
Define a class with keyword “class” followed by name of the class. Define the constructor method using “__construct” followed by arguments. The object of the class can then be instantiated using “new ClassName( arguments_list )” Define class variables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With