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.

1
  • If at least part of it "seems quite easy", what have you tried? Commented Jul 25, 2016 at 8:56

1 Answer 1

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()

Sign up to request clarification or add additional context in comments.

3 Comments

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 :).
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!
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.