Skip to content

Conversation

@vitek-dev
Copy link

  • bug fix / new feature: new feature
  • BC break? no
  • doc PR: nette/docs#??? will write if accepted

While using Nette/Schema I found little discomfort when using PHP 8 features - specifically Constructor property promotion.

Let's imagine following class:

class Foo
{
  public function __construct(
    public int $a,
    public int $b,
  ) {
  }
}

Casting to this class will result in ArgumentCountError because Schema is instantiating the class using new keyword.
This can be solved with instantiating the class using Reflection and it's newInstanceWithoutConstructor method.

I solved this with adding second argument to castTo: castTo(string $type, bool $usingReflection = false): self - default behavior is not changed so it's not causing BC break.

Tests included and passing.

} elseif ($this->castUsingReflection) {
try {
$reflection = new ReflectionClass($this->castTo);
$instance = $reflection->newInstanceWithoutConstructor();
Copy link
Contributor

@JanTvrdik JanTvrdik Jun 20, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about sth like

new ($this->castTo)(...$value);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can probably have part of params promoted by constructor and part of params directly as class properties, reflection got them all.

@dg dg force-pushed the master branch 2 times, most recently from 38fdffd to 343b9dd Compare October 13, 2022 01:24
@dg dg force-pushed the master branch 4 times, most recently from ff661fd to aafca03 Compare January 19, 2023 03:49
@dg dg force-pushed the master branch 2 times, most recently from 0df20de to 36932a7 Compare January 26, 2023 22:50
@vitek-dev vitek-dev closed this by deleting the head repository Feb 4, 2023
dg added a commit that referenced this pull request Oct 3, 2023
dg added a commit that referenced this pull request Oct 3, 2023
dg added a commit that referenced this pull request Oct 3, 2023
dg added a commit that referenced this pull request Oct 4, 2023
dg added a commit that referenced this pull request Oct 4, 2023
dg added a commit that referenced this pull request Oct 4, 2023
dg added a commit that referenced this pull request Oct 5, 2023
dg added a commit that referenced this pull request Oct 5, 2023
dg added a commit that referenced this pull request Oct 5, 2023
dg added a commit that referenced this pull request Oct 5, 2023
dg added a commit that referenced this pull request Oct 5, 2023
dg added a commit that referenced this pull request Oct 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants