1 year ago
#382347
Vincent
Is using get_object_vars() or json_encode() very bad for encapsulation?
Solution found in the comment: use the JsonSerializable interface
I am looking for the most proper way to create an array from an object properties.
The object properties would would have to store the keys and values pairs I need in the array.
I do know that get_object_vars() and json_encode() will retrieve public class fields only, but that lead to some issues regarding encapsulation.
Which method below would be considered as the best practice?
Using public fields with get_object_vars
In that case, the fields name must match with the array keys I need.
class Foo{
public string $name;
// Method is kind of optional since the field is public
public function setName(string $name):void{
$this->name = $name;
}
}
$foo = new Foo();
$foo->setName('bar');
var_dump(get_object_vars($foo));
- Pros: Super straightforward
- Cons: No encapsulation. Fields I need to make the array must be set to public
Using an intermediate class to build the array
class Foo{
private string $name;
public function setName(string $name):void{
$this->name = $name;
}
public function getName():string{
return $this->name;
}
}
$foo = new Foo();
$foo->setName('bar');
$builder = new ArrayBuilderFromFoo($foo);
var_dump($builder->createArray());
- Pros: Encapsulation
- Cons: Need an intermediate object to create the array
Storing the properties in an array field and using an extra-method to retrieve the array
class Foo{
private array $properties;
public function setName(string $name):void{
$this->properties['name'] = $name;
}
public function getProperties():array{
return $this->properties;
}
}
$foo = new Foo();
$foo->setName('bar');
var_dump($foo->getProperties());
- Pros: Encapsulation
- Cons: A little less straight forward than using get_object_vars on the object. On a side note, I also lose the possibility to call json_decode directly on the object.
I know that class fields should be made private whenever it is possible to do so. Best practice advice on this use case is welcome.
php
encapsulation
0 Answers
Your Answer