Skip to content

promoted & hooked property type declaration #17877

@procodix

Description

@procodix

Description

Consider the class below:

Property should be of type string(!), however when initializing the object through the constructor, a string|float union type should be accepted - doing conversions within the setter hook to store a string finally.

The compiler does not allow passing a float, since promoted property type is a string.

However changing the property's type to string|float is not wanted, since it would loosen the type requirements/hinting at other places.

Without the promoted property it works as expected.

The following code:

<?php

// not working within promoted property
class Test {
	public function __construct(
		public string $Property {
			set(string|float $value) {match (true) {
				is_string($value) => $this->Property = $value,
				is_float($value) => $this->Property = (string) $value,	
			};}
		}
	) {}
}

class Test2 {
	public function __construct(string|float $property)	{
		$this->Property = $property;	
	}
	
	public string $Property {
		set(string|float $value) {match (true) {
			is_string($value) => $this->Property = $value,
			is_float($value) => $this->Property = (string) $value,	
		};}
	}
}

PHP Version

PHP 8.4

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions