基本上,思路如下:
正在从数据库查询创建对象。它的一个字段包含一个编码的字符串,该字符串在 getter 中解码。
问题是我需要创建此对象的部分副本。此副本应包含编码的字符串,而不是解码的版本。显然,当我尝试直接复制值时,它会调用 getter。
除了在没有 getter 的情况下创建字段的副本之外,是否有针对此类问题的解决方法?
上级:我正在使用神奇的方法,不完全是一个getter(我的糟糕,第一个问题)
public function __get($property){
...
case 'version':
return $this->_getVersion();
}
克隆对象不是这种情况,因为第二个对象也来自数据库,只需要替换一些字段,例如
$item1->version = $item2->version;
所以最后我找到了最好的方法。
我所做的是将解码函数从__get()移动到__set()方法。我现在只将编码的字符串存储在数据库中,解码的数组只存储在模型中。
通过这样做,我确保字段中保存的数据是相同的类型。我还检查数组是否存储在字段中。这表示数据是否已解码。
class AClass
{
private $someProperty = 'SSBwcm92aWRlIHRoZSBiZXN0IHNvbHV0aW9ucyE=';
public function getSomeProperty()
{
return base64_decode($this->someProperty);
}
}
// Get the instance.
$object = new AClass;
// Get the property.
$property = (new ReflectionClass($object))->getProperty('someProperty');
// Make it accessible.
$property->setAccessible(true);
// Get the value of the property for the instance.
echo $property->getValue($object);
输出:
SSBwcm92aWRlIHRoZSBiZXN0IHNvbHV0aW9ucyE=