0

I am currently playing a little bit with PHP and tried to find a way to convert a class to data I can save in a database ( array / JSON / key value ).

Till that it seems quite easy to use get_obj_vars or cast to array. But later I want to load the data from the database and convert it back to the class I had before so I can continue to work with the data in class format.

Example :

class TestClass {
    private $name;
    private $number;
    private $testClass2;
    /* getter + setter */
}

class TestClass2 {
    private $name;
    private $number;
    /* getter + setter */
}

$testclass = new TestClass();
$testclass2 = new TestClass2();
$testclass2->setName("Class2");
$testclass2->setNumber(42);

$testclass->setName("MyName");
$testclass->setNumber(23);
$testclass->setTestClass2($testclass2);

Now I want to convert $testclass to something I can save in the database in a "key-value-table". After that I want to recreate the class with the given data from database.

Ephenodrom
  • 1,797
  • 2
  • 16
  • 28

1 Answers1

1

I think what you're looking for is how to serialize and unserialize data in PHP.

Try looking at: How to use php serialize() and unserialize()

Community
  • 1
  • 1
  • Yeah this looks great. Is there a way where I can define the return type of the unserialize method ? So my IDE can autofill the method names :). – Ephenodrom Jul 25 '16 at 09:07
  • Not sure if your IDE supports it -- you'd have to check the docs. Usually in IntelliJ (PHP Storm) return types are specified using the @return annotation in the doc block. By specifying the correct type the IDE should pick-up the correct class methods to auto-complete. Hope that helps! – Albert Rannetsperger Jul 25 '16 at 09:19
  • Yeah of course I can add the @return annotation. But thats static, i would like to dynamically define the return type. If I unserialize CLASS A i want to define the return type to be CLASS A. If i unserialize CLASS B i want to define the return type to be CLASS B. Otherwise i have to define for each class a method with the equivalent return type. – Ephenodrom Jul 25 '16 at 09:24