Menu
CoddyTech

方法和独立状态

Coddy 面向 Rust 开发者的 PHP 课程的第 31 课,共 48 课。

Rust 接收器(如 &self 和 &mut self)声明了允许的访问方式,而所有权会限制别名。PHP 方法使用 $this,不会在编译时进行借用检查。请确保每个实例的状态彼此独立,并测试多个对象,以发现意外共享状态或更新了错误接收器的情况。

实例方法使用 $this 访问当前对象。方法调用使用 ->。每个实例都有自己的普通属性,因此重置一个对象不应重置另一个对象。对于每个实例各自的状态,请避免使用静态属性。即使方法的类型正确,如果它更新了错误的实例,行为仍然可能不正确。

Rust 程序

struct Counter{n:i32}
impl Counter{fn add(&mut self,x:i32){self.n+=x;}}
fn main() {
let mut counter=Counter{n:2}; counter.add(3); println!("{}",counter.n);
}

源程序输出:

5

PHP 程序

demo.php

<?php
declare(strict_types=1);
class Toggle {private bool $on=false;public function flip():void{$this->on=!$this->on;}public function label():string{return $this->on?"on":"off";}} $a=new Toggle();$b=new Toggle();$a->flip();echo $a->label(),":",$b->label(),"\n";

PHP 输出:

on:off
challenge icon

挑战

简单

输入是一个由非负整数增量组成的列表。Counter 从零开始;add(int $amount):void 会增加其私有总数,value():int 会读取该总数。每个新建的 Counter 都彼此独立。

提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。请实现模块声明,不要打印内容;不要替换启动文件,也不要从模块中读取输入。输入符合给定的类型和范围。

编辑 Counter.php。main.php 是锁定的入口文件。依赖项通过 require_once __DIR__ 和相对文件名引入。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Counter.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function counterReport(array $values):int{$c=new Counter();foreach($values as $v)$c->add($v);return $c->value();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new Counter();$b=new Counter();$a->add(3);$a->add(2);ensure($a->value()===5 && $b->value()===0,"instance state");
echo (string)counterReport($input),"\n";
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Rust 开发者的 PHP中的所有课

自己练习: PHP 在线编译器