1

I am new to getters and settings, and want to start trying them. I see how I can retrieve a single property, but how can I receive retrieve properties or all of them in JSON format such as {"firstField":321, "secondField":123}. I've tried public function get(){ return $this;} and even public function getJson(){return json_encode($this);} but just get empty JSON.

PS. Is return $this; in the setter a typo or does it provide some value?

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>

Reference https://stackoverflow.com/a/4478690/1032531

user1032531
  • 22,993
  • 61
  • 191
  • 346
  • 2
    Implement JsonSerializable interface – NobbyNobbs May 28 '18 at 19:50
  • 3
    `return $this` it isn't typo, it's make method chainable. – NobbyNobbs May 28 '18 at 19:53
  • @NobbyNobbs Thanks for the chainable comment. Still looking into http://php.net/manual/en/jsonserializable.jsonserialize.php. Seems like a lot of work, and am hoping that getters and setters are actually a good thing. I know some don't like magic methods, but the issues are the same even if I don't use them. – user1032531 May 28 '18 at 20:01
  • Why do you think implementation of JsonSerializable is look like a lot of work? You need implement only one method which just returns assoc array like this `['prop1'=>$this->prop1, 'prop2'=>$this->prop2]` – NobbyNobbs May 28 '18 at 20:31
  • @NobbyNobbs I don't think it is a lot of work (anymore). It works great. Thanks! – user1032531 May 28 '18 at 20:40

1 Answers1

0

Highly inspired by NobbyNobbs.

abstract class Entity implements \JsonSerializable
{
    public function __get($property) {
        if (property_exists($this, $property)) return $this->$property;
        else throw new \Exception("Property '$property' does not exist");
    }

    public function __set($property, $value) {
        if (!property_exists($this, $property)) throw new \Exception("Property '$property' is not allowed");
        $this->$property = $value;
        return $this;
    }
}

class Something extends Entity
{
    protected $name, $id, $data=[];

    public function jsonSerialize()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'data' => $this->data
        ];
    }
}
user1032531
  • 22,993
  • 61
  • 191
  • 346