简体   繁体   中英

cakephp - How can I set a default value of a variable passed from controller to view?

I am still new in CakePHP.
I have a controller which set variable "V1" when some conditions are met.
Now, I want to make this "V1" has a default value of '' or null when I don't set it so cakephp will not throw a notice "error: variable 'V1' not set".
I tried <?= $V1 = '' ?> in view but this cause "V1" to be always empty even after I've set it before at controller.
Question: Should I just ignore this notice or is there a way to set a default value for a variable passed from Controller to View? Or is there any other way?

Thank you :D

This should work

    <?= isset($v1)?$v1:''?>

edit: fixed closing tag

Question: Should I just ignore this notice or is there a way to set a default value for a variable passed from Controller to View? Or is there any other way?

All notices and warnings should be fixed - always , no exception. Not doing so can lead to nasty to debug issues within the application. It's simply bad practice to not fix them. So either make sure it variable is always set or check for it in the view.

Doing this in your controller will ensure it's always set to the view with a default value of null .

$this->set('v1', isset($v1) ? $v1 : null)

php7 with coalescing operator .

$this->set('v1', $v1 ?? null);

However, I prefer the ternary operator here because it's better to read than the coalescing operator - IMHO.

Just to add to burzum's answer. If you're working with PHP 7 you can also use the null coalescing operator in your controller:-

$this->set('v1', $v1 ?? null);

See the PHP docs for further details.

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.

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