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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.