关注"问题"
PHP类具有很多属性.很多Getters/Setter.
有没有什么好的解决方案将所有属性转换为数组?
protected $name;
protected $date;
public function getName();
public function getDate();
public function asArray(); // call all getters?
Run Code Online (Sandbox Code Playgroud)
Tim*_*thy 10
您的API是否已经定义,是否仍然存在getX和setX方法?我更喜欢物业.减少输入,更好地区分属性和方法,结果代码看起来更像PHP,而不像Java.但暴露属性并不意味着你失去了封装并使你的所有内部公开.使用__get和__set魔术方法,您可以对所呈现的内容进行相当精细的控制.另外,将属性转储为数组是相当简单的:
class Foo
{
protected $properties;
public function __construct() {
$this->properties = array();
}
public function __set($prop, $value) {
$this->properties[$prop] = $value;
}
public function __get($prop) {
return $this->properties[$prop];
}
public function toArray() {
return $this->properties;
}
}
Run Code Online (Sandbox Code Playgroud)
唉,如果你因为胡思乱想的老板或者对OOP 必须有什么误解而坚持使用setter/getter ,为什么不把对象强制转换为数组呢?
class Bar
{
public $x;
public $y;
public $z;
protected $a;
protected $b;
protected $c;
private $q;
private $r;
private $s;
public function __construct() {
}
public function setA($value) {
$this->a = $value;
}
public function getA() {
return $this->a;
}
public function setB($value) {
$this->b = $value;
}
public function getB() {
return $this->b;
}
public function setC($value) {
$this->c = $value;
}
public function getC() {
return $this->c;
}
public function toArray() {
return (array)$this;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意如何转换public,protected和private属性:
$bar = new Bar();
print_r($bar->toArray());
array(9) {
["x"]=>
NULL
["y"]=>
NULL
["z"]=>
NULL
[" * a"]=>
NULL
[" * b"]=>
NULL
[" * c"]=>
NULL
[" Foo q"]=>
NULL
[" Foo r"]=>
NULL
[" Foo s"]=>
NULL
}
Run Code Online (Sandbox Code Playgroud)
请注意,protected/private的数组键不以空格开头,它是null.您可以重新键入它们,甚至可以根据需要过滤掉受保护/私有属性:
public function toArray() {
$props = array();
foreach ((array)$this as $key => $value) {
if ($key[0] != "\0") {
$props[$key] = $value;
}
}
return $props;
}
Run Code Online (Sandbox Code Playgroud)
你正在使用动态语言; 利用它,享受它!