LoginSignup
2
4

More than 5 years have passed since last update.

PHPでGetterとSetterを書きたい

Posted at

基本系でリアルに書く

  • リアルに書くとIDEで補完に出てくれます。
  • PHPStormを使っている場合は、
    • Alt + Insert > [Getter and Setters...]
    • で作れます。手で書くとつらいので。
/** Ponsukeのクラス. */
class Ponsuke
{
    /** @var string 住処. */
    private $place;

    /**
     * 住処を取得する.
     * @return string|null 住処.
     */
    public function getPlace(): string
    {
        return $this->place;
    }

    /**
     * 住処を設定する.
     * @param string $place 住処.
     */
    public function setPlace(string $place)
    {
        $this->place = $place;
    }
}

マジックメソッドで書く

  • マジックメソッドを書いただけではIDEで補完に出ません。
  • classのPHPDocに@methodを書いてあげると補完に出ます。
    • ただし、@methodで補完に出るようになりますが、マジックメソッドを書き忘れても補完に出ます。
    • 結果、実行するとエラーになります:hearts:
/**
 * Ponsukeのクラス.
 * @method string getPlace()
 * @method void setPlace(string $value)
 */
class Ponsuke
{
    /** @var string 住処. */
    private $place;

    /**
     * Getter.
     * @param $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->$name;
    }

    /**
     * Setter.
     * @param $name
     * @param $value
     */
    public function __set($name, $value)
    {
        $this->$name = $value;
    }
}

参考

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4