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戻ります0bucket配列の0番目の要素であるため)-これは for にキャストさfalseれますif

于 2012-10-19T02:35:18.347 に答える