5

PHP Tricks: Lazy public readonly properties

 2 years ago
source link: https://www.garfieldtech.com/blog/phptricks-lazy-public-readonly-properties
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PHP Tricks: Lazy public readonly properties

Submitted by Larry on 12 November 2021 - 10:50am

I am apparently late in coming to this trick, but PHP 8.1 is going to make it even nicer to use.

A clever trick

There's an interesting intersection of functionality in PHP:

  • Declared object properties are more efficient than dynamic ones, because the engine can make assumptions about what data type to expect.
  • The magic `__get()` and `__set()` methods trigger when there is no property with a given name that has been *set*.
  • Fun fact: A property that has been declared but not initialized with a value is still technically "set"... to `uninitialized`.
  • However, you can `unset()` an uninitialized property.

That means you can do clever tricks like this (and some systems do, internally):

Continue reading this post on PeakD


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK