note 129716 added to language.oop5.anonymous

From: Date: Thu, 22 Aug 2024 19:38:52 +0000
Subject: note 129716 added to language.oop5.anonymous
Groups: php.notes 
Request: Send a blank email to php-notes+get-221490@lists.php.net to get a copy of this message
Thanks to the new property hooks in PHP 8.4 (https://wiki.php.net/rfc/property-hooks) and anonymous functions, now we can create an inner class instantiated only on use: <?php class BaseClass { public function __construct() { echo "base class\n"; } public $childClass { set {} get { if ($this->childClass === null ) { $this->childClass = new class { public function __construct() { echo " child class\n"; } public function say(string $s) : void { echo " $s\n"; } }; } return $this->childClass; } } } $base = new BaseClass(); $base->childClass->say('Hello'); $base->childClass->say('World'); /* Output: base class child class Hello World */ ?> The obvious downside is that you can't set a type to the child class, unless you define an interface and the child class implements it or if the child class extends an existing class: <?php class ParentClass { public function say(string $s) : void { echo " $s\n"; } } class BaseClass { public function __construct() { echo "base class\n"; } public ParentClass $childClass { set {} get { if (!isset($this->childClass)) { $this->childClass = new class extends ParentClass { public function __construct() { echo " child class\n"; } }; } return $this->childClass; } } } $base = new BaseClass(); $base->childClass->say('Hello'); $base->childClass->say('World'); /* Output: base class child class Hello World */ ?> ?> This can be also done with functions, but with hooks to me looks more like in other languages that have this functionality natively. ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 45.134.213.198) ---- Manual Page -- https://php.net/manual/en/language.oop5.anonymous.php Edit -- https://main.php.net/note/edit/129716 Del: integrated -- https://main.php.net/note/delete/129716/integrated Del: useless -- https://main.php.net/note/delete/129716/useless Del: bad code -- https://main.php.net/note/delete/129716/bad+code Del: spam -- https://main.php.net/note/delete/129716/spam Del: non-english -- https://main.php.net/note/delete/129716/non-english Del: in docs -- https://main.php.net/note/delete/129716/in+docs Del: other reasons-- https://main.php.net/note/delete/129716 Reject -- https://main.php.net/note/reject/129716 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221490) next »