iT邦幫忙

2025 iThome 鐵人賽

DAY 5
0
Modern Web

Laravel 是甚麼系列 第 5

函式是甚麼

  • 分享至 

  • xImage
  •  

Return表示得到的結果

https://ithelp.ithome.com.tw/upload/images/20250806/20119035qT75XRSGYe.png

<?php

function getWeight()
{
   $myWeight = 70;
   $food = 5;
   return $myWeight + $food;
}

echo(getWeight());

Return表示得到的結果75


function getWeight($food)表示參數$food
50表示參數$food的數字

https://ithelp.ithome.com.tw/upload/images/20250806/20119035bicnBgpvxY.png

<?php

function getWeight($food)
{
  $myWeight = 70;    
  return $myWeight+$food ;
}

echo(getWeight(50));

得到70+50=120
物件概念
public所有人都可以使用
$this表示這個物件

https://ithelp.ithome.com.tw/upload/images/20250806/20119035ONkXcQ9pfT.png

<?php

class People
{
   public $weight = 70;
   public function getWeight()
   {
       return $this->weight;
   }
   public function eat($food)
   {
       $this->weight += $food;
       return $this->weight;
   }
}

$people = new People;
echo($people->getWeight()."\r\n");
echo($people->eat(10)."\r\n");
echo($people->getWeight()."\r\n");

echo($people->getWeight()."\r\n");得到70
echo($people->eat(10)."\r\n");加入吃的就是70+10
echo($people->getWeight()."\r\n");吃完部會馬上消失就是80

物件的繼承
Joe繼承people體重80公斤
不用多寫就可以自動繼承people
https://ithelp.ithome.com.tw/upload/images/20250806/20119035gHwMHNvrWl.png
對照看
echo($joe->getWeight()."\r\n");得到50
echo($joe->eat(10)."\r\n");加入吃的就是50+10
echo($joe->getWeight()."\r\n");吃完部會馬上消失就是60

<?php
class People
{
   public $weight = 70;
   public function getWeight()
   {
       return $this->weight;
   }
   public function eat($food)
   {
       $this->weight += $food;
       return $this->weight;
   }
}

class Joe extends People
{
   public $weight = 50;
}

$joe = new Joe;
echo($joe->getWeight()."\r\n");
echo($joe->eat(10)."\r\n");
echo($joe->getWeight()."\r\n");

題目:得到寶可夢目前的能量
100-20=80
80*2=160

https://ithelp.ithome.com.tw/upload/images/20250806/201190353ENIkAPhSP.png

<?php
class Pokemon
{
  public $hp = 100;
  public $attack = 30;
  public function attacked($attack)
  {
      $this ->hp -=$attack;
  }
  public function evolve()
  {
      $this ->hp *=2;
      $this ->attack *=2;
  }
  public function getHp()
  {
      return $this ->hp;
  }
}
$pokemon = new Pokemon;
$pokemon->attacked(20);
$pokemon->evolve();
echo($pokemon->getHp());

PHP常用函式
array_column
array_keys
array_values
調整內容array_map
只挑要的array_filter
增加值array_push
把最後一個值取出array_pop
合併array_merge
排序sort
array_search搜尋
array_unique濾掉重複
總加總array_sum
計算count
https://ithelp.ithome.com.tw/upload/images/20250806/201190350kEf9XemrT.png
大家明天見~


上一篇
資料結構
下一篇
就是安裝
系列文
Laravel 是甚麼30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言