Skip to main content
3 of 3
added a note about an OOP replacement to drupal_static(), on Drupal 8.6
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

drupal_static() is used to cache data within a single page request. it stores the data in a static variable.
The class returned by \Drupal::state() handles values that need to be preserved between requests. As such, it is probable it stores its values in a database table. (It depends from the exact implementation done from that class.)

drupal_static() is faster since it saves its values in the memory, but using states doesn't make a lot of difference.

As for recommending one, both are recommended. It's up to you using the one that suits your needs. Do you need a cross-request value, or a value you use only in one request?

If you are looking to replace drupal_static() with OOP code, Drupal 8.6 introduced the MemoryCache class, that stores cache items in memory using a PHP array. It has been added to allow classes that would previously maintain state on a protected property (as a static cache to avoid persistent cache or database lookups) to inject a service to hold that state instead. (See Added memory cache.)
Notice that the class isn't used directly. The module needing it should define a new service, similarly to what Drupal core does with the entity.memory_cache service.

entity.memory_cache:
  class: Drupal\Core\Cache\MemoryCache\MemoryCache
avpaderno
  • 97.9k
  • 15
  • 164
  • 284