Is there a way to reduce the many properties of an object?

Since I'm lazy, I was wondering if PHP has a short way to set such properties ...

with $person_object { ->first_name = 'John'; ->last_name = 'Smith'; ->email = ' spam_me@this-place.com '; } 

Is there anything similar? Or is there a lazy way to set properties without retyping $person_object ?

+4
source share
4 answers

You can implement something similar to a builder pattern in your Person class. The approach involves returning $this at the end of each setter call.

 $person ->set_first_name('John') ->set_last_name('Smith') ->set_email(' spam_me@this-place.com '); 

And in your class ...

 class Person { private $first_name; ... public function set_first_name($first_name) { $this->first_name = $first_name; return $this; } ... } 
+8
source

No.

No no.

+2
source

A common decoration function can do this for you:

 function decorate( $object, $data ) { foreach ( $data as $key => $value ) { $object->$key = $value; } } decorate( $person_object, array( 'first_name' => 'John', 'last_name' => 'Smith' ) ); 

I may have made some mistakes, it has been a while since I wrote the PHP code and this has not been verified

+2
source

No, I do not think so. You could do such a thing:

 class Person { function __call($method, $args) { if (substr($method, 0, 3) == set) { $var = substr($method, 3, strlen($method)-3); $this->$var = $args[0]; } else { //throw exception } } } 
+1
source

Source: https://habr.com/ru/post/1389522/


All Articles