19
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

19
12
2

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
19
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?