方法与独立状态
Coddy 面向 C 开发者的 PHP 课程的第 31 课,共 48 课。
C 语言中类似实例的辅助函数接收一个指向其要修改结构体的显式指针。PHP 实例方法使用 $this 作为当前接收者。独立的对象保留各自独立的普通属性,而静态属性会引入共享状态。请确认每个方法更新的都是目标实例。
实例方法使用 $this 来访问当前对象。方法调用使用 ->。每个实例都拥有自己的普通属性,因此重置一个对象不应该重置另一个对象。避免将静态属性用于单个实例的状态。即便一个方法在类型上是正确的,如果它更新了错误的实例,其行为依然可能是错误的。
C 程序
#include <stdio.h>
struct Counter { int n; };
static void counter_add(struct Counter *self, int amount)
{
self->n += amount;
}
int main(void)
{
struct Counter counter = {2};
counter_add(&counter, 3);
counter_add(&counter, 4);
printf("%d\n", counter.n);
return 0;
}源输出:
9PHP 程序
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挑战
简单输入是一个非负整数增量列表。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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 PHP中的所有课
自己练习: PHP 在线编译器