Php что означает знак вопроса
Перейти к содержимому

Php что означает знак вопроса

  • автор:

Php что означает знак вопроса

(PHP 4, PHP 5, PHP 7, PHP 8)

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to true , PHP will execute statement , and if it evaluates to false — it'll ignore it. More information about what values evaluate to false can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b :

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b , and would then assign the value of $a into $b :

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

Знак вопроса перед параметром метода это ошибка в PHP?

Встретил в чужом коде такую вещь.
Функционал работает нормально, а IDE подсвечивает ошибкой.
Ошибка ли это ? что может означать?
5ae6d093d95e1581548878.png

  • Вопрос задан более трёх лет назад
  • 5378 просмотров

Простой 1 комментарий

  • Facebook
  • Вконтакте
  • Twitter

Типы для параметров и возвращаемых значений могут быть помечены как обнуляемые путем добавления префикса в виде знака вопроса. Это означает, что указанные параметры и возвращаемые значения, могут быть как указанного типа, так и NULL.

What are the PHP operators "?" and ":" called and what do they do?

Peter Mortensen's user avatar

means «if $x is true, then use $y ; otherwise use $z «.

It also has a short form.

means «if $x is true, then use $x ; otherwise use $z «.

People will tell you that ?: is «the ternary operator». This is wrong. ?: is a ternary operator, which means that it has three operands. People wind up thinking its name is «the ternary operator» because it’s often the only ternary operator a given language has.

chaos's user avatar

I’m going to write a little bit on ternaries, what they are, how to use them, when and why to use them and when not to use them.

What is a ternary operator?

A ternary ? : is shorthand for if and else . That’s basically it. See «Ternary Operators» half way down this page for more of an official explanation.

As of PHP 5.3:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

As of PHP 7.0

PHP 7 has new Null Coalesce Operator. This is the same as a ternary but is also called an «isset ternary». This also allows a set of chained ternaries that remove the need for isset() checks.

In PHP 5, if you wanted to use a ternary with a potentially non-existent variable then you would have to perform an isset() at the beginning of the ternary statement:

In PHP 7, you can now do this instead:

The Null Coalesce Operator does not work with an empty string, however, so bear that in mind. The great thing about this is you can also chain the operators for multiple checks for multiple variables, providing a sort of backup depending on whether or not each variable in the chain exists:

In PHP, with systems where a user can login, it is not uncommon for an administrator to be able to impersonate another user for testing purposes. With the above example, if the user is not impersonating another user, and also a logged in user does not exist, then the user will be a guest user instead. Read on more if you don’t understand this yet to see what ternaries are and how they are used, and then come back to this bit to see how the new PHP

How are ternaries used?

Here’s how a normal if statement looks:

Let’s shorten that down into a ternary.

Much shorter, but maybe harder to read. Not only are they used for setting variables like $var in the previous example, but you can also do this with echo , and to check if a variable is false or not:

Why do people use them?

I think ternaries are sexy. Some developers like to show off, but sometimes ternaries just look nice in your code, especially when combined with other features like PHP 5.4’s latest short echos.

Going off-topic slightly, when you’re in a ‘view/template’ (if you’re seperating your concerns through the MVC paradigm), you want as little server-side logic in there as possible. So, using ternaries and other short-hand code is sometimes the best way forward. By «other short-hand code», I mean:

Note, I personally do not like this kind of shorthand if / endif nonsense

How fast is the ternary operator?

People LIKE micro-optimisations. They just do. So for some, it’s important to know how much faster things like ternaries are when compared with normal if / else statements.

Reading this post, the differences are about 0.5ms. That’s a lot!

Oh wait, no it’s not. It’s only a lot if you’re doing thousands upon thousands of them in a row, repeatedly. Which you won’t be. So don’t worry about speed optimisation at all, it’s absolutely pointless here.

When not to use ternaries

Your code should be:

  • Easy to read
  • Easy to understand
  • Easy to modify

Obviously this is subject to the persons intelligence and coding knowledge / general level of understanding on such concepts when coming to look at your code. A single simple ternary like the previous examples are okay, something like the following, however, is not what you should be doing:

That was pointless for three reasons:

  • Ridiculously long ternary embedding
  • Could’ve just used a switch statement
  • It was orange in the first place

Conclusion

Ternaries really are simple and nothing to get too worked up about. Don’t consider any speed improvements, it really won’t make a difference. Use them when they are simple and look nice, and always make sure your code will be readable by others in the future. If that means no ternaries, then don’t use ternaries.

php Два знака вопроса что это ?? — Null-коалесцентный оператор

vedro-compota's picture

Два знака вопроса, идущие подряд без пробела (впервые появились появились в php7) — это не что иное как:

Null-коалесцентный оператор

Решает распространенную проблему в PHP.
Она возникает в случае, если мы хотим присвоить значение переменной, которое присвоено другой переменной, но если последней переменной значение не было присвоено (isset), то присвоить некое явное значение по умолчанию.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *