1
0

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のfunction __constract() について整理する

Last updated at Posted at 2021-07-03

コンストラクタとは

コンストラクタはクラスの中で定義するメソッドで、クラスがインスタンス化(NEW)したときに自動的に実行されるもの。
インスタンスを生成したときに初期化する際に、コンストラクタが用いられる。

class Product
{
	function __construct() {
            $this->price = 100;
            $this->tax_rate = 0.1;
	}
	function totalPrice() {
	    return $this->price * (1 + $this->tax_rate);
	}
}

コンストラクタの実行

//インスタンス化した時点で、コンストラクタは実行されている
$product = new Product();

//コンストラクタ以外のメソッドは使いたい時に呼び出す
$product->totalPrice(); //110が表示される

コンストラクタに引数を設定する場合

class Product
{
    private  $name;
	private  $price;
	private  $tax_rate;
 
	function __construct($name, $price, $tax_rate) {
		$this->name = $name;
		$this->price = $price;
		$this->tax_rate = $tax_rate;
	}
        function totalPrice() {
		return $this->price * (1 + $this->tax_rate);
	}
}

インスタンスを生成

//コンストラクタの引数に$price=200, $tax_rate=0.1を代入してインスタンス化した場合

$pencil = new Product('えんぴつ', 200, 0.1);
echo $pencil->name . 'は、' . $pencil->totalPrice() . '円です'; 
//えんぴつは220円です

結論

__constractはクラスのインスランスを生成した時に必ず実行されるメソッド

参考文献
以下のサイトを参照して記事を書かせていただきました。
https://uxmilk.jp/14376

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?