skip to Main Content

I would like to know if I can use Partial like typescript.

For instance I have this class:

class Registration {
    public function __construct(
        public readonly int $year,
        public readonly int $coverage,
        public readonly string $start_date,
        public readonly string $state_address,
    ) {
    }
}

Is there a way to create a class from the original (without modifying it) but make it "Partial". Where all attributes are optional or null. Something like this:

class RegitrationPartial extends Partial(Registration) { }

Now I can call that class in this way:

new RegitrationPartial(year: 2025);

2

Answers


  1. You can use something called named arguments, this allows you to specify the exact argument you want to populate. Your actually pretty close already.

    <?php
    
    class Registration {
        public function __construct(
            public readonly ?int $year = null,
            public readonly ?int $coverage = null,
            public readonly ?string $start_date = null,
            public readonly ?string $state_address = null,
        ) {
            //
        }
    }
    
    $Registration = new Registration(year: 2025);
    

    Some further reading on named arguments
    https://stitcher.io/blog/php-8-named-arguments

    Login or Signup to reply.
  2. You can create a RegistrationPartial class that extends the original class and uses optional parameters in its constructor, providing null as default values. after that, you can send those optional parameters to the parent class based on whether they are provided or not.

    this one should work:

    class Registration {
        public function __construct(
            public readonly int $year,
            public readonly int $coverage,
            public readonly string $start_date,
            public readonly string $state_address
        ) { }
    }
    
    class RegistrationPartial extends Registration {
        public function __construct(
            ?int $year = null,
            ?int $coverage = null,
            ?string $start_date = null,
            ?string $state_address = null
        ) {
            parent::__construct(
                $year ?? 0, // Provide default or placeholder value
                $coverage ?? 0,
                $start_date ?? '',
                $state_address ?? ''
            );
        }
    }
    
    // Usage:
    $partial = new RegistrationPartial(year: 2025);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search