0

我遇到了以下类抛出无法解释的异常的问题...

<?php
abstract class Search_Options {

    protected $options = array();

    public function __construct($options = array()) {
        foreach ($options as $option => $value) {
            $this->setOption($option, $value);
        }
    }

    public function getOption($option) {
        return $this->options[$option];
    }

    public function setOption($option, $value) {
        $option = strtolower($option);
        if (array_search($option, $this->allowed)) {
            $this->options[$option] = $value;
            return $this;
        }
        throw new Exception($option." is not allowed.");
    }

    public function build() {
        return $this->options;
    }

    protected function between($x, $y, $z) {
        return (($x <= $y) && ($y <= $z));
    }
}

class Artist_Search extends Search_Options {

    protected $allowed = array(
        "bucket",
        "results",
        "start",
        "limit"
    );

    public function bucket($bucket) {
        $bucket = (!is_array($bucket)) ? array($bucket) : $bucket;
        return $this->setOption("bucket", $bucket);
    }

    public function results($results) {
        if ($this->between(0, $results, 100)) {
            return $this->setOption("results", $results);
        }
        throw new Exception("results must be between 0..100, supplied ".$results);
    }

    public function start($start) {
        return $this->setOption("start", $start);
    }

    public function limit($limit) {
        if (is_bool($limit)) {
            return $this->setOption("limit", $limit);
        }
        throw new Exception("limit must be true|false, supplied ".$limit);
    }
}
?>

如果我运行以下命令,它可以正常工作...参见示例:http ://codepad.org/ZXD2ZGEo

$s = new Artist_Search();
$q = $s->results(10)->start(5)->limit(true)->build();
print_r($q);

Array
(
    [results] => 10
    [start] => 5
    [limit] => 1
)

但是,当我尝试同时调用 Artist_Search::bucket() 时,出现错误...参见示例:http ://codepad.org/vwr7UrpG

$s = new Artist_Search();
$q = $s->bucket(array("familiarity"))->results(10)->start(5)->limit(true)->build();

print_r($q);

Fatal error: Uncaught exception 'Exception' with message 'bucket is not allowed.' in /t.php:22
Stack trace:
#0 /t.php(45): Search_Options->setOption('bucket', Array)
#1 /t.php(68): Artist_Search->bucket(Array)
#2 {main}
  thrown in /t.php on line 22
4

1 回答 1

4

in_array不使用array_search

在您的情况下array_search返回0(因为bucket是数组的第 0 个元素) - 它被强制转换falseif

于 2012-10-19T02:35:18.347 回答