Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array_filter anonymous function passing $this [duplicate]

Tags:

php

if want to do this following:

    $filteredValues = array_filter($rawValues, function($rawValue) {
        return $this->validateValue($rawValue);
    });

validateValue is a private method in the same class.

How can i use $this context in array_filter in this way?

like image 397
Marty Wallace Avatar asked Aug 07 '26 07:08

Marty Wallace


1 Answers

If you use PHP 5.3, PHP does not recognize $this as closure, you need to do a trick like JavaScript:

$self = $this;
$filteredValues = array_filter($rawValues, function($rawValue) use ($self) {
    return $self->validateValue($rawValue);
});

Note that the above will only give you access to the object through the public API of the object. This is different from the 5.4 support for Closure rebinding which allows full access to $this.

like image 126
cuongle Avatar answered Aug 08 '26 23:08

cuongle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!