0
1

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 3 years have passed since last update.

PHP クラスの使い方 勉強メモ

Last updated at Posted at 2020-07-05

クラスの使い方のmemo

クラスの使い方
// クラス
class Post
{
  // プロパティ
  private $text;
  private $likes;
  
  // コンストラクタ
  public function __construct($text, $likes)
  {
    $this->text = $text;
    $this->likes = $likes;
  }

  // メソッド
  public function show()
  {
    printf('%s (%s)' . PHP_EOL, $this->text, $this->likes);
  }
}

//ここで値を渡す
$posts[0] = new Post('hello', 0);
$posts[1] = new Post('hello again', 1);

//Postクラスのshowメソッドを実行
$posts[0]->show();
$posts[1]->show();

出力される値
hello (0)
hello again (0)

コンストラクタ

・newしたときに実行される特殊なメソッド

クラスを定義する理由

・修正を加えるときに影響範囲がわかりやすい。(コードの見通しがよくなる)

アクセス修飾子

*初期値や何も記載しない場合は、public
*意図しない使われ方をしないために、privatがいいかも。

public

クラスの中でも外でも使える

private

クラス内でしか使えない変数に定義する。

protected

親クラスと子クラスで使える

継承

final

メソッドをオーバーライドしてほしくないときに利用する
例:

final public function test() {
   echo 'test';
}

参考
ドットインストール
https://dotinstall.com/lessons/basic_php_objects/54004

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?