LoginSignup
12

More than 5 years have passed since last update.

staticメソッドは$this->でも呼べる

Last updated at Posted at 2012-12-10

static::doSomething()で呼ぶ必要があるのだと勘違いしてた。

<?php
class Hoge {
  static function foo() {
    //この中で$thisは使えない
    echo 'Hoge::foo';
  }

  function hoo() {
    $this->foo();
  }
}

$hoge = new Hoge;
$hoge->foo(); //一切エラーは発生しない
$hoge->hoo(); //一切エラーは発生しない

staticにすると$thisが使えなくなり、プロパティの読み書きもできず、かなり制約がきつくなる。むしろ積極的に使うと、インスタンスの状態変更を行っていないことを明示できて読みやすいコードになるかも。

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
12