【问题标题】:How can I overwrite a protected property of an object?如何覆盖对象的受保护属性?
【发布时间】:2017-08-02 00:14:29
【问题描述】:

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

【问题讨论】:

  • 为什么会从144变成18?你真正想做什么?
  • @Ohgodwhy 我正在尝试做this

标签: php laravel


【解决方案1】:

你可以使用反射:

$reflection = new \ReflectionObject($followers);

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

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

参考见:

【讨论】:

  • 9001 是什么?
  • totals 属性的任意新值。
【解决方案2】:

你应该创建一个 getter 和 setter 函数。

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

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

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

【讨论】:

猜你喜欢
  • 2012-01-31
  • 2019-05-31
  • 2013-07-01
  • 1970-01-01
  • 2013-12-18
相关资源
最近更新 更多