Home » Php » PHP 5.3.0 USE keyword — how to backport in 5.2?

PHP 5.3.0 USE keyword — how to backport in 5.2?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have some code that has been written in for php 5.3.0 using the USE function within PHP

can someone help me change this to work for 5.2.9?

$available  = array_filter($objects, function ($object) use ($week) { 
    return !in_array($object, $week);
});

thanks for the help

How to&Answers:

Not nice, but this would be an equivalent implementation.

class MyWeekFilter {
    protected $_week;

    public function __construct($week) {
        $this->_week = $week;
    }

    public function filter($object) {
        return !in_array($object, $this->_week);
    }
}

$filter    = new MyWeekFilter($week);
$available = array_filter($objects, array($filter, 'filter'));

Answer:

Is there any difference between author’s code

$available = array_filter($objects, function ($object) use ($week) { 
    return !in_array($object, $week);
});

and

$available = array_diff($objects, $week);

?

Answer:

$available  = array_filter($objects, create_function('$object', '
    $week = '.var_export($week,true).';
    return !in_array($object, $week);
'));

Answer:

Try this:

$week = array(...); // defined and instantiated before...

function callback($object) {
    return !in_array($object, $week);
}
$available  = array_filter($objects, "callback");