Reputation:
I'm getting an error, never had before. I don't know the meaning exactly or how I can fix it
trait Test{
function init(){
$req = $this->getRequest();
usort($req['topics], function($first, $next) {
if(is_null($first['expiryDate'])) return 1;
if(is_null($next['expiryDate'])) return -1;
// otherwise ascending
return $first['expiryDate'] > $next['expiryDate'];
});
}
}
this is my class
class SchedulerRepository extends Repository implements SchedulerInterface
{
use Test;
protected Collection $request;
protected array $topics;
/**
* @return Collection
*/
public function getRequest(): Collection
{
return $this->request;
}
public function bootstrap($data)
{
$this->request = $data;
dd($this->init());
}
}
The error i'm getting
"message": "Indirect modification of overloaded element of Illuminate\\Support\\Collection has no effect",
"exception": "ErrorException",
the error is in my Trait exactly in the first parameter of usort
function
I tried to Google the issue, but no luck
Thanks for the help
Upvotes: 0
Views: 683
Reputation: 55427
The fast fix is to create a temporary variable based on the array index, sort that, and set it back. Also, comparison functions should return integers, not booleans, <=>
should be used instead of >
.
trait Test {
function init(){
$req = $this->getRequest();
$topics = $req['topics'];
usort($topics, function($first, $next) {
if(is_null($first['expiryDate'])) return 1;
if(is_null($next['expiryDate'])) return -1;
// otherwise ascending
return $first['expiryDate'] <=> $next['expiryDate'];
});
$req['topics'] = $topics;
}
}
You can see a mocked demo here: https://3v4l.org/qLN2l
The longer answer has to do with Collection
which implements ArrayAccess
. The latter interface allows user-land code to be interacted with using array-like semantics, specifically []
, through class methods. Anytime you see []
a call to offsetGet
happens on the object, and this returns a copy of the array. The notice exists to warn you that your changes would be lost.
Upvotes: 2