I’m getting the error Using $this when not in object context when using the code below. Is this because the function is on the stack and has no access to the object?
array_walk($pins, function (&$array) {
$array->timestamp = $this->convertTime(strtotime($array->timestamp));
});
What’s the best way to get around this? I was thinking of using a foreach, but wanted to learn more of PHP’s lesser used functions that suit the purpose.
Solved it with
foreach($pins as $pin) {
$pin->timestamp = $this->convertTime(strtotime($pin->timestamp));
}
But I would still like to know how to get around the issue with array_walk.
I would say for your case,
foreachis a very good solution because it’s clear what it does. You might want to mimic the aliasingarray_walkoffers with your example:This should come more closely to
array_walk. Probably you want to reference the array itself as well (probably):If you want to encapsulate the object itself (
$this) inside an anonymous function with private access, this is not possible. Because there does not exists any$thisin the context of the anonymous function (yet, a later PHP version might have that).However one workaround is to pass the object instance into the local scope of the anonymous function by making use of the
useclause.But this workaround is limited, as private members of
$thisare not accessible. Instead you can create the callback function as part of your object and specify it, private access is possible then and you can invoke it like any other object callback:Which brings me back to the beginning saying that
foreachis probably the better weapon of choice thanarray_walkin your case.I hope this is helpful to show you the different alternatives.