ThinkPHP 3.2.3 这个三元表达式的写法有什么错误?

WBOY
Release: 2016-06-06 20:07:36
Original
1265 people have browsed it

下面这种写法有什么错误? session不能用于三元表达式吗?

<code>$data['user_id'] = isset(session('user_id')):session('user_id'):'guest';</code>
Copy after login
Copy after login

回复内容:

下面这种写法有什么错误? session不能用于三元表达式吗?

<code>$data['user_id'] = isset(session('user_id')):session('user_id'):'guest';</code>
Copy after login
Copy after login

建议你这样写

<code>$data['user_id'] = session('user_id');
if (empty($data['user_id'])) $data['user_id'] = 'guest';</code>
Copy after login

三元方式建议为

<code>$data['user_id'] = session('user_id') ? session('user_id') : 'guest';</code>
Copy after login

isset用来检测变量是否已经声明,而不是用来检查值的,否则会产生语法错误。

三元表达式
condition ? p1 : p2

你两个都是 :

http://php.net/manual/zh/language.operators.comparison.php#language.operators.comparison.ternary

你写成两个:了,$data['user_id'] = session('user_id') ? session('user_id') : 'guest';

<code>$data['user_id'] = isset(session('user_id'))?session('user_id'):'guest';</code>
Copy after login

首先如上所说,判断条件后应该是?号
第二,isset传参不能是函数返回值

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template