Differences from objects

Although Enums are built on classes and objects, they do not support all object-related functionality. In particular, Enum cases are forbidden from having state.

  • Constructors and Destructors are forbidden.
  • Inheritance is not supported. Enums may not extend or be extended.
  • Static or object properties are not allowed.
  • Cloning an Enum case is not supported, as cases must be singleton instances.
  • Magic methods, except for those listed below, are disallowed.
  • Enums must always be declared before they are used.

The following object functionality is available, and behaves just as it does on any other object:

  • Public, private, and protected methods.
  • Public, private, and protected static methods.
  • Public, private, and protected constants.
  • Enums may implement any number of interfaces.
  • Enums and cases may have attributes attached to them. The TARGET_CLASS target filter includes Enums themselves. The TARGET_CLASS_CONST target filter includes Enum Cases.
  • __call, __callStatic, and __invoke magic methods
  • __CLASS__ and __FUNCTION__ constants behave as normal

The ::class magic constant on an Enum type evaluates to the type name including any namespace, exactly the same as an object. The ::class magic constant on a Case instance also evaluates to the Enum type, as it is an instance of that type.

Additionally, enum cases may not be instantiated directly with new, nor with ReflectionClass::newInstanceWithoutConstructor() in reflection. Both will result in an error.

<?php
$clovers 
= new Suit();
// Error: Cannot instantiate enum Suit
$horseshoes = (new ReflectionClass(Suit::class))->newInstanceWithoutConstructor()
// Error: Cannot instantiate enum Suit
?>

Here you can write a comment


Please enter at least 10 characters.
Loading... Please wait.
* Pflichtangabe
There are no comments available yet.

PHP cURL Tutorial: Using cURL to Make HTTP Requests

cURL is a powerful PHP extension that allows you to communicate with different servers using various protocols, including HTTP, HTTPS, FTP, and more. ...

TheMax

Autor : TheMax
Category: PHP-Tutorials

Midjourney Tutorial - Instructions for beginners

There is an informative video about Midjourney, the tool for creating digital images using artificial intelligence, entitled "Midjourney tutorial in German - instructions for beginners" ...

Mike94

Autor : Mike94
Category: KI Tutorials

Basics of views in MySQL

Views in a MySQL database offer the option of creating a virtual table based on the result of an SQL query. This virtual table can be queried like a normal table without changing the underlying data. ...

admin

Autor : admin
Category: mySQL-Tutorials

Publish a tutorial

Share your knowledge with other developers worldwide

Share your knowledge with other developers worldwide

You are a professional in your field and want to share your knowledge, then sign up now and share it with our PHP community

learn more

Publish a tutorial