0

I've a persistent library that should store objects in a database. So var_export() should store the type, pk, and db-version only. At the reverse it should recreated the object from the database using the key. In other words:

class Person
{
  use PersistTrait; // $id, $store, __get, __set

  protected string $name;
  protected string $website;

  public function __construct(string $id)
  {
    // connect to db
    // retrieve object content by $id
  }
  public static function __set_state($array_with_only_id): Person
  {
    // check version
    return new self( $array_with_only_id['id'] ); // exception when not found etc.
  } 
}

$person = new \Person();
$person->name = 'ElePHPant ElePHPantsdotter';
$person->website = 'https://php.net/elephpant.php';
$person->store();

$c = var_export($person);
// $c should only contain "
Person::__set_state(
  [
    'id'=>'pk-value-of-person',
    'version'=>'db-version'
  ]
);

Is this possible?

5
  • 4
    Why var_export()? __serialize()/__unserialize() already provides this functionality. Commented Jun 12 at 16:35
  • Note also, your constructor is spelled wrong, and if it were spelled correctly, you'd have a required argument that you don't pass when you instantiate. You've also got protected attributes that you're trying to directly manipulate outside the class. Commented Jun 12 at 16:43
  • As noted, the built-in serialize functions can handle this for you, and you can elevate those to one or more traits (or include it with your existing trait even): 3v4l.org/tQ21K
    – Chris Haas
    Commented Jun 12 at 17:46
  • @AlexHowansky Serializable::serialize()and Serializable::unserialize() would be different use cases, wouldn't they? I'm not sure why __serialize()/__unserialize() exist. But yes, var_export() probably is concepted for a specific use case I'm not aiming here.
    – theking2
    Commented Jun 12 at 21:47
  • @AlexHowansky setting/getting protected properties is handled by the trait. as they indicate a 'dirty' instance.
    – theking2
    Commented Jun 12 at 21:50

1 Answer 1

0

The var_export() aims one very specific use case: convert a construct (array, object) in a language specific string form that can be used to recreate the object. Much like Serializable::serialize() and Serializable::unserialize() combo but with the class type included. It was not meant to be used in a more generic use case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.