gremo
gremo

Reputation: 48899

PHP making a protected property public at runtime

Problem: I don't want to expose $myProperty, that is it shouldn't be public, but I need it to be public just for __toString():

class A
{
    protected $myProperty;

    public function __toString()
    {
        return json_encode($this);
    }
}

I know that ReflectionProperty class has a method named setAccessible(), but how I'm supposed to use it before returning the string?

EDIT: as per comments, I need compatibility with PHP 5.3.x, that is no JSonSerializable class.

Upvotes: 0

Views: 437

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

Why don't you simply build a PHP stdClass object and then serialize it to JSON, since when you deserialize from JSON, that is exactly what you get anyway.

Maybe something like this:

public function __toString() {
   $return = new stdClass();
   $properties = get_object_vars($this);
   foreach ($properties as $key => $value) {
       $return->$key = $value;
   }
   return json_encode($return);
}

Upvotes: 0

hakre
hakre

Reputation: 197659

As per PHP 5.3 use get_object_vars inside the __toString() method:

public function __toString()
{
    return json_encode(get_object_vars($this));
}

Usage Demo:

class A
{
    protected $myProperty = 'hello';

    public function __toString()
    {
        return json_encode(get_object_vars($this));
    }
}

echo new A; 

Output:

{"myProperty":"hello"}

Tip: Create the JsonSerializable interface your own and implement the jsonSerialize() method your own to be upwards compatible. Call the function when you need it and/or call it inside __toString():

public function __toString()
{
    return json_encode($this->jsonSerialize());
}

Upvotes: 3

Related Questions