简体   繁体   English

如何将一个函数的结果作为另一个函数的默认值传递?

[英]How can I pass the result of a function as a default value of another function?

I have a function that is called without the user giving notice, and it just creates a row on my Database. 我有一个无需用户通知就可以调用的函数,它只是在数据库上创建一行。
The function is this one: 功能是这个:

public function createRow($year = 2015) {
    $query = DB::table('myTable')->where('year', '=', $year)->get()->first();
    // The rest of the function doesn't matter
}

The problem here is that I need the default value for this function to be the year before the actual year. 这里的问题是我需要将此功能的默认值设置为实际年份之前的年份。 In order to do that I tried to put this: 为了做到这一点,我试图把它:

public function createRow($year = date('Y') - 1) {
    $query = DB::table('myTable')->where('year', '=', $year)->get()->first();
    // whatever
}

It's obvious it didn't work, so I did a really small function that return the year before the actual year, and I tried to use the result of the small function as the default parameter of the createRow() function: 显然它没有用,所以我做了一个很小的函数,该函数返回实际年份的前一年,并且我尝试使用该小函数的结果作为createRow()函数的默认参数:

public function lastYear() {
   return date('Y') - 1;
}
public function createRow($year = $this->lastYear()) {
    $query = DB::table('myTable')->where('year', '=', $year)->get()->first();
    // Whatever
}

I also tried defining a global variable: 我也尝试定义一个全局变量:

protected $lastYear = date('Y') - 1;

but I got the error: 但我得到了错误:

expression is not allowed as field default value 表达式不能作为字段默认值

I hope you can help me with this. 希望您能帮到我。

Thank you very much. 非常感谢你。

Try this: 尝试这个:

public function createRow($year = null) {
    if ($year == null)
    {
        $year = date('Y') - 1;
    }
    $query = DB::table('myTable')->where('year', '=', $year)->get()->first();
    // whatever
}

Try this 尝试这个

public function createRow($year) {

    if (!$year)
    {
        $year = date('Y') - 1;
    }

    $query = DB::table('myTable')->where('year', '=', $year)->get()->first();
    // whatever
}

You can change the if condition so if $year does not contain a valid value you can set the it the default value in the beginning of the function. 您可以更改if条件,以便如果$ year不包含有效值,则可以在函数开头将其设置为默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM