【发布时间】:2025-12-20 11:20:09
【问题描述】:
我对@987654321@ 的工作方式感到困惑。让我再详细说明一下这个问题。
通常我们使用这样的接口:
<?php
interface Countable {
/* Methods */
public function count();
}
class MyThings implements Countable
{
public function count() {
return count($this->arrayOfThings);
}
}
$obj = new MyThings();
//call count method on $obj
$obj->count();
所以我们有一个类,它实现了接口。当我们调用count()函数时,它已经写在MyThings类中了。这很容易理解。
但是当我们像这样使用JsonSerializable接口时:
<?php
class Thing implements JsonSerializable {
public function jsonSerialize() {
// do something
}
}
$obj = new Thing();
//call count method on $obj
json_encode($obj);
jsonSerialize() 内部 Thing 与 json_encode() 调用一起运行。
如果我们打电话是可以理解的
$obj->jsonSerialize();
然后在类中有一个名为jsonSerialize() 的函数。但是,当我们运行json_encode() 时,它是如何工作的?这是如何在php中构建的?有人能解释一下这里使用的是什么类型的模式吗?
【问题讨论】:
标签: php