5
6

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.

[PHP]抽象クラス

Last updated at Posted at 2014-09-30

なにか?

  • 継承先クラスで、定義する必要があるメソッドを、定義のみする

なぜ使うか?

  • 定義する必要があり、実装が呼び出し先で違う時、定義を強制することができる。
  • 制約できるので、コード書きながら設計している気分になれる

サンプルコード

abstract.php
<?php

abstract class Working
{
    abstract protected function where();
    abstract protected function why();
    abstract protected function how();

    public function work()
    {
    	echo $this->where($where);
    	echo $this->why($reason);
    	echo $this->how($how);
    }
}

class Person extends Working
{
	protected function where()
	{
		return '横浜で';
	}

	protected function why()
	{
		return 'お金欲しいから';
	}

	protected function how()
	{
		return '営業する';
	}
}

$bob = new Person();
$bob->work(); // 横浜でお金欲しいから営業する

MORE

書いていて、これは便利なのでは、と思った。
継承元見た時に、処理フローがわかりやすい。

5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?