轨道
/
PHP
PHP
/
练习
/
Lucian 的美味千层面
Lucian 的美味千层面

Lucian 的美味千层面

学习练习

简介

基础

想了解这些主题的更多细节,请访问概念页面。

通用语法

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

说明

在本练习中,你将编写一些代码,帮助你照着最喜欢的烹饪书做出一份美味的千层面。

共有 5 个任务,都与烹饪千层面所花的时间有关。

1. 定义预期的烤箱时间(分钟)

在Lasagna类中实现expectedCookTime函数,它不接收任何实参,返回千层面应该在烤箱里烤多少分钟。 根据烹饪书,预期的烤箱时间是 40 分钟:

<?php
$timer = new Lasagna();
$timer->expectedCookTime()
// => 40

2. 计算剩余的烤箱时间(分钟)

在Lasagna类中实现remainingCookTime函数,它接收千层面已经在烤箱里烤了多少分钟作为实参,并根据上一个任务中得出的预期烤箱时间,返回千层面还需要在烤箱里烤多少分钟。

<?php
$timer = new Lasagna();
$timer->remainingCookTime(30)
// => 10

3. 计算准备时间(分钟)

在Lasagna类中实现totalPreparationTime函数,它接收你往千层面里加了多少层作为实参,返回你准备千层面花了多少分钟,假设每准备一层需要 2 分钟。

<?php
$timer = new Lasagna();
$timer->totalPreparationTime(3)
// => 6

4. 计算总工作时间(分钟)

在Lasagna类中实现totalElapsedTime函数,它接收两个实参:第一个实参是你往千层面里加了多少层,第二个实参是千层面已经在烤箱里烤了多少分钟。 该函数应返回你烹饪千层面总共工作了多少分钟,也就是准备时间的分钟数,加上此刻千层面在烤箱里所花的时间。

<?php
$timer = new Lasagna();
$timer->totalElapsedTime(3, 20)
// => 26

5. 创建一条千层面已做好的通知

在Lasagna类中实现alarm函数,它不接收任何实参,返回一条表示千层面可以开吃了的消息。

<?php
$timer = new Lasagna();
$timer->alarm()
// => "Ding!"
通过 GitHub 编辑 链接将在新窗口或新标签页中打开
PHP Exercism

准备好开始 Lucian 的美味千层面 了吗?

注册 Exercism,借助 11 个概念122 个练习 和真人导师指导,学习并掌握 PHP,全部免费。