如何覆盖对象的受保护属性?

时间:2017-07-31 05:16:02

标签: php laravel

这是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;

2 个答案:

答案 0 :(得分:1)

你可以使用反射:

$reflection = new \ReflectionObject($followers);

$property = $reflection->getProperty('total');

$property->setAccessible(true);
$property->setValue(
    $followers,
    18
);

供参考,见:

答案 1 :(得分:0)

你应该制作一个getter和setter函数。

但您可以使用PHP-Reflections。像这个例子:

<?php
class LengthAwarePaginator
{
    private $total = true;
}

$class = new ReflectionClass("LengthAwarePaginator");
$total = $class->getProperty('total');
$total->setAccessible(true);
$total->setValue(18);
相关问题