2

I am looking for a way to mark a field, and use that mark later for different operation on the object.

For example, serialize object without the marked fields:

class A(){
   public $field1;

   //@dont_serialize
   public $field2;
} 

$obj = new A();
$obj->field1 = "important data";
$obj->field2 = "not important data";

function MySerialize($obj){
  $arr = (array) $obj;
  $new_arr = array();   
  foreach ($arr as $key => $value) {
      if (THIS FEILD IS NOT MARKED AS @dont_serialize)
      {
        $new_arr[$key] = $value
      }
  }
  return serialize($new_arr);
}

How can I implement MySerialize() that will not serialize marked fields ?

Grigory Ilizirov
  • 1,030
  • 1
  • 8
  • 26
  • 1
    Without reflection (which would be a serious hack) you probably want to build an array of fields to serialize or not serialize. – AbraCadaver Apr 20 '16 at 20:11

3 Answers3

1

You need to read your annotation and process it, good example is in this answer: https://stackoverflow.com/a/9742661/3354887

Also there is a docblock parser: https://github.com/doctrine/annotations

Community
  • 1
  • 1
smoq
  • 130
  • 2
  • 6
1

To go forward with reflection API you should "mark" your fields with "appropriate"(formatted) comment.
Here is working solution using ReflectionClass class, ReflectionProperty::getDocComment, ReflectionProperty::getName and ReflectionProperty::getValue methods:

class A {

    public $field1;
    public $field2;

    /**
     * @dont_serialize
     */
    public $field3;

}

$obj = new A();
$obj->field1 = "important data";
$obj->field2 = "needed data";
$obj->field3 = "not important data";

function MySerialize($obj) {
    $reflector = new ReflectionClass(get_class($obj));
    $props = $reflector->getProperties();
    $new_arr = [];

    foreach ($props as $property) {
        if (strpos($property->getDocComment(), "@dont_serialize") === false) {
            $new_arr[$property->getName()] = $property->getValue($obj);
        }
    }
    return serialize($new_arr);
}

print_r(MySerialize($obj));

The output:

"a:2:{s:6:"field1";s:14:"important data";s:6:"field2";s:11:"needed data";}"
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

Just for the serialize purpose, there is a better approach, instead of marking the properties and use reflection.

There are, magic functions __sleep(), __wakeup()... allowing to change the fields that will be serialized with serialize() function for details look at http://php.net/language.oop5.magic

Grigory Ilizirov
  • 1,030
  • 1
  • 8
  • 26