PHP 8.5.0 Alpha 2 available for testing

Voting

: two plus four?
(Example: nine)

The Note You're Voting On

ismaelj+php at hotmail dot com
11 months ago
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.

<< Back to user notes page

To Top