rfc:property-capture

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
Next revisionBoth sides next revision
rfc:property-capture [2023/04/15 20:28] – created imsoprfc:property-capture [2023/04/15 20:51] imsop
Line 33: Line 33:
 $bar = 2; $bar = 2;
 $anon = new class($foo, $bar) { $anon = new class($foo, $bar) {
-    public $foo; +    var $foo; 
-    public $bar;+    var $bar; 
 +    
     public function __construct($foo, $bar) {     public function __construct($foo, $bar) {
         $this->foo = $foo;         $this->foo = $foo;
Line 41: Line 42:
 }; };
 </code> </code>
- 
-==== Visibility Modifiers ==== 
  
 ==== Renaming ==== ==== Renaming ====
 +
 +By default, the property takes the same name as the outer variable, but this can be over-ridden using the syntax ''$varName as $propName''. This also allows the same local variable to be captured as the initial value for more than one property. For example:
 +
 +<code php>
 +$foo = 1;
 +$bar = 2;
 +$anon = new class use ($foo as $one, $bar as $two, $bar as $three) {};
 +</code>
 +
 +Is equivalent to:
 +
 +<code php>
 +$foo = 1;
 +$bar = 2;
 +$anon = new class($foo, $bar, $bar) {
 +    var $one;
 +    var $two;
 +    vat $three;
 +    
 +    public function __construct($one, $two, $three) {
 +        $this->one = $one;
 +        $this->two = $two;
 +        $this->three = $three;
 +    }
 +};
 +</code>
 +
 +==== Modifiers and Type ====
 +
 +The ''as'' keyword can also be used to modify the visibility and/or type of the declared property, either instead of or as well as renaming the property.
 +
 +The modifiers allowed are the same as for Constructor Property Promotion, which is used internally to declare the properties; that is currently:
 +
 +  * One of ''public'', ''protected'', or ''private''
 +  * Optional ''readonly'', which must be combined with a type specification
 +  * A type specification
 +
 +For example:
 +
 +<code php>
 +$foo = 1;
 +$bar = 2;
 +$anon = new class use ($foo as private, $bar as protected readonly int, $bar as ?int $alsoBar) {};
 +</code>
 +
 +Is equivalent to:
 +
 +<code php>
 +$foo = 1;
 +$bar = 2;
 +$anon = new class($foo, $bar, $bar) {
 +    private $foo;
 +    protected readonly int $bar;
 +    var ?int $alsoBar;
 +    
 +    public function __construct($foo, $bar, $alsoBar) {
 +        $this->foo = $foo;
 +        $this->bar = $bar;
 +        $this->alsoBar = $alsoBar;
 +    }
 +};
 +</code>
 +
  
 ===== Restrictions and Errors ===== ===== Restrictions and Errors =====
rfc/property-capture.txt · Last modified: 2023/04/23 21:15 by imsop