想更深入了解這些主題,請參閱概念頁面。
PHP 的起始標籤<?php代表 PHP 程式碼的開頭。
所有敘述都必須以;結尾,用來分隔指令。
<?php
$message = "Success!"; // Statement correctly ends with `;`
$message = "I fail." // PHP Parse error: syntax error, [...]
為了方便閱讀,所有程式碼範例都省略了 PHP 起始標籤<?php。
單行註解以//開頭。
// Single line comment
使用賦值運算子=,就能把值指定給變數。
變數名稱必須以美元符號$開頭,並遵循命名慣例。
$count = 1; // Assign value of 1
// Strings can be created by enclosing the characters
// within single `'` quotes or double `"` quotes.
$message = "Success!";
值與變數可以傳遞給函式。
函式的引數會成為新的變數,用來保存傳入的值。
函式可以使用關鍵字return回傳任何值。
function window_height($height)
{
return $height + 10;
}
window_height(100);
// => 110
類別及其實例內部的函式稱為方法。
要呼叫方法時,實例會接在方法名稱前面,中間用->。
方法可以存取特殊變數$this,它指向目前的實例。
<?php
class Calculator {
public function sub($x, $y)
{
return $this->add($x, -$y); // Calls the method add() of the current instance
}
public function add($x, $y)
{
return $x + $y;
}
}
$calculator = new Calculator(); // Creates a new instance of Calculator class
$calculator->sub(3, 1); // Calls the method sub() of the instance stored in $calculator
// => 2
在這個練習中,你會寫一些程式碼,幫助你照著最愛的食譜做出一份美味的千層麵。
你有五個任務,全都和烹調千層麵所花的時間有關。
在 Lasagna 類別中實作 expectedCookTime 函式,它不接受任何引數,並回傳千層麵應該待在烤箱裡幾分鐘。
根據食譜,預期的烤箱時間是 40 分鐘:
<?php
$timer = new Lasagna();
$timer->expectedCookTime()
// => 40
在 Lasagna 類別中實作 remainingCookTime 函式,它接受千層麵實際已經待在烤箱裡的分鐘數作為引數,並根據上一個任務算出的預期烤箱時間,回傳千層麵還需要在烤箱裡待幾分鐘。
<?php
$timer = new Lasagna();
$timer->remainingCookTime(30)
// => 10
在 Lasagna 類別中實作 totalPreparationTime 函式,它接受你加在千層麵裡的層數作為引數,並回傳你準備千層麵花了幾分鐘,假設每一層要花你 2 分鐘準備。
<?php
$timer = new Lasagna();
$timer->totalPreparationTime(3)
// => 6
在 Lasagna 類別中實作 totalElapsedTime 函式,它接受兩個引數:第一個引數是你加在千層麵裡的層數,第二個引數是千層麵已經待在烤箱裡的分鐘數。
這個函式應該回傳你烹調千層麵總共花了幾分鐘,也就是準備時間的分鐘數,加上千層麵當下已經待在烤箱裡的分鐘數。
<?php
$timer = new Lasagna();
$timer->totalElapsedTime(3, 20)
// => 26
在 Lasagna 類別中實作 alarm 函式,它不接受任何引數,並回傳一則訊息,表示千層麵可以吃了。
<?php
$timer = new Lasagna();
$timer->alarm()
// => "Ding!"