0

I am starting to learn PHP and have a decent Java background. I came upon the following coding challenge in the PHP langauge:

I want to be able to encode/decode my PHP classes in JSON format. I have created PHP classes that utilize getter/setter methods for the classes private properties. This caused the native json_encode method to skip skip these properties during encoding. I found the following script which picks up private properties and formats them in a JSON string:

<?php
public function encodeJSON()
{
    foreach ($this as $key => $value)
    {
        $json->$key = $value;
    }
    return json_encode($json);
}
public function decodeJSON($json_str)
{
    $json = json_decode($json_str, 1);
    foreach ($json as $key => $value)
    {
        $this->$key = $value;
    }
}
?>

I studied up on this code and realized how it was generating the strings and objects. Now I would like to push this code into an abstract class, so that I may extend that class and receive this functionality.

The problem is I cannot reference the private properties in the concrete class from the abstract class. My knowledge of Java tells me that I may not be able to do this without specifying an abstract method and forcing each concrete class to implement it. I tried several attempts at using reflection in PHP and passing the concrete class into the constructor of the abstract class. Can anyone point me in the right direction or just tell me if this isn't possible?

2
  • 1
    Does it work with protected? (The concept of private variables is not to be able to see them in delivered classes so it's correct behavior) Commented Feb 9, 2012 at 12:07
  • @Vyktor Yes it does. I was so focused on learning the new stuff that I forgot and neglected my basic programming foundation. Thank you for picking that up. If you post it as an answer I'll accept. Commented Feb 9, 2012 at 12:13

1 Answer 1

1

The concept of private variables is not to be able to see them in delivered classes so it's correct behavior.

If you use protected instead your concept should work just fine.

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

2 Comments

thanks again. I'm so used to serializing and deserializing with Jackson in Java, which allows me to keep the fields private that I neglected the idea of scope
PHP provides two ways of serialization, one is implementing __sleep and __wakeup (sk.php.net/manual/en/language.oop5.magic.php#object.sleep) and Serializable interface (sk.php.net/manual/en/class.serializable.php) which we had nice discussion about here: stackoverflow.com/questions/9114368/…

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.