Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand way to set many object properties?

Tags:

php

Because I'm lazy I was wondering if PHP has a shorthand way to set properties like this...

with $person_object {
    ->first_name = 'John';
    ->last_name = 'Smith';
    ->email = '[email protected]';
}

Is there anything like this? Or, is there a lazy way to set properties without having to type $person_object over and over again?

like image 275
noctufaber Avatar asked Dec 10 '22 03:12

noctufaber


1 Answers

You could implement something akin to the builder pattern within your Person class. The approach involves returning $this at the end of every setter call.

$person
    ->set_first_name('John')
    ->set_last_name('Smith')
    ->set_email('[email protected]');

And in your class...

class Person {
    private $first_name;
    ...
    public function set_first_name($first_name) {
        $this->first_name = $first_name;
        return $this;
    }
    ...
}
like image 112
Finbarr Avatar answered Jan 02 '23 10:01

Finbarr