用2个不同的条件变量做1个if代码.或者类似的东西


Doing 1 if code with 2 different condition variables... Or something like this

我想用这个可能的参数创建一个函数:s

  • leFunction ((string) $type,(string) $data),这很简单,switch根据给定类型定义$return(做任何switch可以用$data做的事情)。例如,我可以发送1865年作为$data,如果$type是"fromYear"和$data是_numeric,它会做它应该做的任何事情。
  • leFunction ((string) $type,(array) $data),这是棘手的地方。我的想法是,有了第二种选择,我可以传递与("fromYear", array("year" => 1865, ....) )相同的参数,然后检查is_numeric($data["year"]),并继续使用相同的代码。

但是当我把这两部分组合在一起的时候,我得到了这个不太好的if:

if (is_numeric($data) || (is_array($data) && isset($data["year"])))

然后我将第二部分替换为来自父对象的函数:

if (is_numeric($data) || is_numeric($this->setIfGet("year", $data)))
func:

/**
     * @param $needle string key
     * @param $haystack array source
     * @param bool $null make true if value of $needle could be null
     * @return bool
     */
    protected function setIfGet($needle, $haystack, $null = false)
    {
        return (isset($haystack[$needle])) ? $haystack[$needle] : ($null) ? (array_key_exists($needle, $haystack) ? $haystack[$needle] : false): false;
    }

但是这里有一个问题:如果我想从$data参数返回year,我需要执行

if (...) {
   echo $data;
    ...
}

但是如果$data是数组并且我想回显的年份在

中,则不起作用
$data["year"];

我想我找到了自己问题的答案:

if (is_numeric($newData = $data) || is_numeric($newData = self::setIfGet("year", $data))){
    echo $newData;
相关文章: