ここまで
--->pencil.php
<!--pencilクラスを作る/非表示-->
<?php
class Pencil{
private $maker;
private $hardness;
private $price;
public function __construct($maker,$hardness,$price){
$this->maker=$maker;
$this->hardness=$hardness;
$this->price=$price;
}
public function setData($maker,$hardness,$price){
$this->maker=$maker;
$this->hardness=$hardness;
$this->price=$price;
}
public function printData(){
echo "メーカー:".$this->maker."<br>";
echo "硬度:".$this->hardness."<br>";
echo "価格".$this->price;
}
}
?>
--->useclass.php
<?php
require_once("pencil.php");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>クラスを使う</title>
</head>
<body>
<h1>クラスを使う</h1>
<?php
$item=new Pencil("トンボ","HB",120);
$item->printData();
?>
</body>
</html>
クラスの定義
class クラス名(){
アクセス修飾子 変数宣言;
アクセス修飾子 メソッドの定義(){
}
}
アクセス修飾子:
public どこからでも
protected 内部と子クラスから
private クラス内部からのみ
コンストラクタ(construct)はオブジェクトを作成するときに一度だけ呼び出される特別なメソッド
アクセス修飾子 function __construct(hoge,hoge2){
}
$this->プロパティ名
でプロパティにアクセスできる
このときプロパティ名の前には$をつけない
今回privateがついているので、useclass.phpで$item->priceなどを使うことはできない
--->自分で手を加えた
pencil.php
<!--pencilクラスを作る/非表示-->
<?php
class Pencil{
private $maker;
private $hardness;
private $price;
private $star;
public function __construct($maker,$hardness,$price){
$this->maker=$maker;
$this->hardness=$hardness;
if ($hardness =="HB"){
$this->star="★★★";
}elseif ($hardness =="B"){
$this->star="★★";
}
$this->price=$price;
}
public function setData($maker,$hardness,$price){//constructで定義したものの書き換え
$this->maker=$maker;
$this->hardness=$hardness;
$this->price=$price;
}
public function printData(){
echo "メーカー:".$this->maker."<br>";
echo "硬度:".$this->hardness."<br>";
echo $this->star."<br>";
echo "価格:".$this->price."円";
echo "<hr>";
}
}
?>
--->useclass.php
<?php
require_once("pencil.php");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>クラスを使う</title>
</head>
<body>
<h1>クラスを使う</h1>
<?php
$item=new Pencil("トンボ","HB",120);
$item->printData();
$item2=new Pencil("ばった","B",80);
$item2->printData();
?>
</body>
</html>
setData()を使う
コンストラクタのif文を通ってないことが分かる