将类函数作为回调传递

时间:2014-07-22 17:07:06

标签: php

我正在尝试做这样的事情:

<?php

class item {
    public $available;
    public $name;

    public function isAvailable() {
        return $this->available;
    }
}

$items = array(new item(), new item(), new item());

function getAvailableItems() {
    return array_filter($GLOBALS['items'], $this.isAvailable);
}

$items[0]->available = false;
$items[0]->name = "x";

$items[1]->available = true;
$items[1]->name = "y";

$items[2]->available = true;
$items[2]->name = "z";

print("First available item " . reset(getAvailableItems())->name);

?>

但我不确定第15行的语法是否正确。我使用的是PHP 5.5.8。

我被建议这样做:

return array_filter($GLOBALS['items'], array($this, 'isAvailable'));

但这也不起作用:

<b>Warning</b>:  array_filter() expects parameter 2 to be a valid callback, first array member is not a valid class name or object on line <b>15</b><br />
<br />
<b>Warning</b>:  reset() expects parameter 1 to be array, null given on line <b>27</b><br />

第一个可用项目

class item {
    public static $available;
    public $name;

    public static function isAvailable() {
        return self::$available;
    }
}

$items = array(new item(), new item(), new item());

function getAvailableItems() {
    return array_filter($GLOBALS['items'], item::isAvailable());
}

$items[0]->available = false;
$items[0]->name = "x";

$items[1]->available = true;
$items[1]->name = "y";

$items[2]->available = true;
$items[2]->name = "z";

print("First available item " . reset(getAvailableItems())->name);

同样发出警告。

我能做到的最好的事情就是:

//<?php

class item {
    public $available;
    public $name;
}

$items = array(new item(), new item(), new item());

function getAvailableItems() {
    return array_filter($GLOBALS['items'], function($item) {
        return $item->available;
    });
}

$items[0]->available = false;
$items[0]->name = "x";

$items[1]->available = true;
$items[1]->name = "y";

$items[2]->available = true;
$items[2]->name = "z";

print("First available item " . reset(getAvailableItems())->name);

//?>

作为匿名函数,它可以工作,但是没有办法传递类函数吗?

1 个答案:

答案 0 :(得分:1)

如果你看到回调中的array_filter php在回调函数中传递了数组的每个值;所以可能的解决方案之一如下: -

<?php

class item {
    public $available;
    public $name;

    public function isAvailable() {
        return $this->available;
    }
}

$items = array(new item(), new item(), new item());

function getAvailableItems() {
    return array_filter($GLOBALS['items'], 'filterItems');
}

function filterItems(item $item) {
    return $item->available;
}

$items[0]->available = false;
$items[0]->name = "x";

$items[1]->available = true;
$items[1]->name = "y";

$items[2]->available = true;
$items[2]->name = "z";

print("First available item " . reset(getAvailableItems())->name); // First available item y