Martin AJ
Martin AJ

Reputation: 6697

How can I overwrite a protected property of an object?

This is the result of 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"
}

Now I want to know, how can I overwrite #total? I mean I want to reinitialize it to 18. So this is the expected result:

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"
}

Is doing that possible?


Noted that none of these work:

$followers->total = 18;
$followers['total'] = 18;

Upvotes: 2

Views: 1085

Answers (2)

wartoshika
wartoshika

Reputation: 541

You should make a getter and setter function.

But you can use PHP-Reflections. Like this example:

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

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

Upvotes: 0

localheinz
localheinz

Reputation: 9582

You could use reflection:

$reflection = new \ReflectionObject($followers);

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

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

For reference, see:

Upvotes: 4

Related Questions