cakephp HttpSocket 响应主体和 body() 之间的区别

cakephp difference between HttpSocket response body and body()

有两种方法可以获取 HttpResponsebody

$http = new HttpSocket();
$response = $http->get('http://www.cakephp.org');
$response->body;

和方法

$http = new HttpSocket();
$response = $http->get('http://www.cakephp.org');
$response->body();

两者 return 相同,但是 属性 和方法之间有什么区别?

我认为该方法是后来添加的,但不确定。 AFAIR 较新的 2.x 版本中的许多方法都从 3 向后移植,以使 API 更加一致,以便仍在使用 Cake2 的人可以将他们的 2.x 应用程序更新到 3.x 接口最终升级时麻烦更少。因此,如果两者都存在,请始终使用 属性 上的方法。

由于技术原因,请参阅此问题:Calling the variable property directly vs getter/setters - OOP Design The reason to use a method over a property is explained in the second answer, the one that has more votes. Alsoe see this one: Properties vs Methods

TL;DR:

You lose the ability to implement special get/set logic on a particular property. For properties that are scalars (strings, integers, booleans) maybe this is no problem. But what if you have a property that is a lazy-loaded class instance?

一个示例是您要解析的 API 响应和 return 其他内容,或者如果 API return 编辑了错误代码则抛出异常。然后扩展 HttpSocket 并重载 body() 方法。

但我建议你阅读整个答案,非常好。