如何覆盖对象的受保护属性?
这是dd($followers)
结果:如何覆盖对象的受保护属性?
LengthAwarePaginator {#401 ▼
#total: 144
#lastPage: 8
#items: Collection {#402 ▼
#items: array:18 [▶]
}
#perPage: 20
#currentPage: 1
#path: "http://myurl.com/SocialCenter/public/twitterprofile/JZarif"
#query: []
#fragment: null
#pageName: "page"
}
现在我想知道,我怎么能覆盖#total
?我的意思是我想将它重新初始化为18
。因此,这是预期的结果:
LengthAwarePaginator {#401 ▼
#total: 18
#lastPage: 8
#items: Collection {#402 ▼
#items: array:18 [▶]
}
#perPage: 20
#currentPage: 1
#path: "http://myurl.com/SocialCenter/public/twitterprofile/JZarif"
#query: []
#fragment: null
#pageName: "page"
}
就是干这个可能吗?
指出,没有任何这些工作:
$followers->total = 18;
$followers['total'] = 18;
您可以使用反射:
$reflection = new \ReflectionObject($followers);
$property = $reflection->getProperty('total');
$property->setAccessible(true);
$property->setValue(
$followers,
18
);
仅供参考,请参阅:
什么是'9001'? –
只是'totals'属性的一个任意的新值。 – localheinz
你应该做一个getter和setter函数。您可以使用PHP-Reflections。像这个例子:
<?php
class LengthAwarePaginator
{
private $total = true;
}
$class = new ReflectionClass("LengthAwarePaginator");
$total = $class->getProperty('total');
$total->setAccessible(true);
$total->setValue(18);
该属性无法访问,您首先需要使用http://php.net/manual/en/reflectionproperty.setaccessible.php。 – localheinz
它为什么会从144变成18?你真的想做什么? – Ohgodwhy
@Ohgodwhy我正在尝试[this](https://stackoverflow.com/questions/45407534/why-are-not-pagination-and-distinct-compatible) –