Home > Backend Development > PHP7 > body text

in PHP7? and? ? What's the difference

醉折花枝作酒筹
Release: 2023-02-17 22:00:01
forward
1769 people have browsed it

This article will introduce to you the difference between "?" and "??" in PHP7. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

in PHP7? and? ? What's the difference

$a = ''; // or 0 or false

$b = $a ?? 'a';
// 此时会判断$a是否存在 $a不为null 
// 等价于
// $b = isset($a) ? $a : 'a';
// $b is '' or 0 or false

$c = $a ?: 'a';
// 此时会判断$a的值
// $c is 'a'
Copy after login
$a = null;

$b = $a ?? 'a';
// 此时$a为null
// $b is  'a'

$c = $a ?: 'a';
// $c is 'a'
Copy after login
$a = null;
$b = 'b';
$c = $a ?? $b ?? 'c';
// 返回第一个有定义的值
// $c is 'b'

$a = null;
$b = null;
$c = $a ?? $b ?? 'c';
// $c is 'c'
Copy after login
function getId(?int $id) {
    return $id;
}
// 参数为指定的整型或空值
getId(857); // 857
getId('857'); // 参数非整型 报错
getId(); // 参数空 报错
getId(''); // 参数非整型 报错
getId(0); // 0
getId(null); // null
Copy after login
function getId():?int
{
	return 1;
}
// 返回值为指定的整型或空值
getId() // 1

function getId():?int
{
	return null;
}
getId() // null

function getId():?int
{
	return '1';
}
getId() // 返回非整型 报错
Copy after login

Recommended learning: php video tutorial

The above is the detailed content of in PHP7? and? ? What's the difference. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!