Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When creating my own classes in PHP should I extend stdClass?

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.

like image 986
sebataz Avatar asked Apr 13 '14 16:04

sebataz


People also ask

What does stdClass mean in PHP?

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.

What does stdClass mean?

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.

How do you create a stdClass object?

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.

How do you declare a class in PHP?

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.


1 Answers

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.

like image 89
Dejan Marjanović Avatar answered Oct 03 '22 18:10

Dejan Marjanović