忍者ブログ

からすまる日誌

20200218pm01 クラスを使う

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

20200218pm01 クラスを使う

ここまで
--->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文を通ってないことが分かる
 
PR

コメント

ブログ内検索

カレンダー

03 2025/04 05
S M T W T F S
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30