Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

Using Typed Properties (PHP 7.4) with Symfony forms

I use DTOs as the data_class for Symfony form types. There is one thing that does not work for me when I use typed properties (PHP 7.4) in these DTOs.

EXAMPLE:

class ProductDto
{
    /*
     * @AssertNotBlank
     */
    public string $title;
}

This generally seems to work quite well – in case the user submits the form with a blank title or description, the validation kicks in and the form is displayed with validation warnings.

BUT THERE IS A PROBLEM when data is added while creating a form (e.g. the edit form):

$productDto = new ProductDto();
$productDto->title = 'Foo';
$form = $this->createForm(ProductFormType::class, $productDto);

Initially the form is displayed as expected with Foo as the value for the title. When a user clears the title input form field and submits the form an exception like this is thrown:

Typed property `AppFormDtoProductDto::$title` must be string, null used

As far as I can see this is caused by the fact that during Form->handleRequest() the title is set to an empty string (or null) after it was set to "Foo" before, right?

Is there a solution for this problem?

question from:https://stackoverflow.com/questions/66065697/using-typed-properties-php-7-4-with-symfony-forms

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since PHP 7.4 introduces type-hinting for properties, it is particularly important to provide valid values for all properties, so that all properties have values that match their declared types.

A property that has never been assigned doesn't have a null value, but it is on an undefined state, which will never match any declared type. undefined !== null.

Here is an example:

<?php

class Foo
{
    private int $id;
    private ?string $val;
    
    public function __construct(int $id) 
    {
        $this->id = $id;
    }
}

For the code above, if you did:

<?php

  foo = new Foo(1);
  $foo->getVal();

You would get:

Fatal error: Uncaught Error: Typed property Foo::$val must not be accessed before initialization

See this post for more details https://stackoverflow.com/a/59265626/3794075 and see this bug https://bugs.php.net/bug.php?id=79620


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...