Return true что это
Перейти к содержимому

Return true что это

  • автор:

What does RETURN TRUE do in a php function?

I was just looking at this code and i don’t understand what RETURN TRUE does or what the point of it is? Can someone please explain?

Thankyou in advance 😉

5 Answers 5

It returns the boolean TRUE to whatever called dance(). That’s all.

You would have to look at the consuming code to see if it makes something from it.

Gordon's user avatar

In that specific piece of code — not very much.

In general however it would be used to return a condition of a validation or code that needs to return either a positive or a negative.

For instance, one would do the following:

because it’s TRUE , elephpant does dance 😉

Sometimes a method/function returns a boolean value to indicate if the operation was succesfull. In the given example it always returns «TRUE».

The calling code can then act upon succesfull completion of the code

if(dance()) echo «succes» else echo «fails»

You can read more about return here: http://www.php.net/return

There are few interesting applications of return like returning value from include -d file.

    The Overflow Blog
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

__return_true() │ WP 3.0.0

Просто возвращает true. Вспомогательная функция WordPress.

Полезна для использования в фильтрах, чтобы вернуть true.

Все подобны функции:
__return_false() — возвращает логическое false.
__return_true() — возвращает логическое true.
__return_empty_array() — возвращает пустой массив: array().
__return_zero() — возвращает число 0.
__return_null() — возвращает NULL.
__return_empty_string() — возвращает пустую строку: ».

return

Оператор return завершает выполнение функции и указывает значение, которое должно быть возвращено вызывающей функции.

Try it

Syntax

Выражение, значение которого должно быть возвращено. Если опущено, вместо этого возвращается undefined .

Description

Когда в теле функции используется оператор return , выполнение функции останавливается. Если указано, вызывающей функции возвращается заданное значение. Например, следующая функция возвращает квадрат своего аргумента x , где x — число.

Если значение опущено, вместо него возвращается undefined .

Все приведенные ниже возвратные сообщения нарушают выполнение функции:

Автоматическая установка точки с запятой

На оператор return влияет автоматическая вставка точки с запятой (ASI) . return и выражением не допускается ограничитель строки .

трансформируется АСИ в

Консоль предупредит «недоступный код после оператора возврата».

Примечание. Начиная с Firefox 40, в консоли отображается предупреждение, если после оператора return обнаружен недостижимый код .

Чтобы избежать этой проблемы (для предотвращения ASI),можно использовать скобки:

JavaScript: What is the return statement?

JavaScript tips & tricks in 3 minutes or less. Today’s topic: return — when to use it and what it does.

If you’re a new developer, it’s important you understand the role of the return statement in JavaScript.

Note: If you’re using Google Chrome, open up your developer console so you can type the examples in and code along. [WINDOWS]: Ctrl + Shift + J [MAC]: Cmd + Opt + J

Rule #1

Every function in JavaScript returns undefined unless otherwise specified.

To test this, we’ll just create an empty function, then invoke it:

As expected, when we invoke our function undefined is returned in the console.

Now we’ll actually specify a return value. Let’s recreate our test() function, but include the return statement this time:

As you can see, our explicitly returned true value replaces the default undefined value.

Rule #2

The return statement ends function execution

This is important. Using return causes your code to short-circuit and stop executing immediately.

Consider this example where we have two return statements in our test function:

The first return statement immediately stops execution of our function and causes our function to return true . The code on line three: return false; is never executed.

Rule #3

The return statement returns a value to the function caller.

In the below example we’re creating a function named double() which returns double the value that is input:

Since a value is being returned to the function caller, we can create a variable and set it equal to an invocation of our function:

Cool. We can even do it again, this time plugging in our six variable into our function:

Ending a Function

Since return stops a function’s execution immediately, it can also be used to interrupt or end a function.

Consider the following example:

In this example, our function countTo() counts up to a user input number. However, if the user doesn’t input a number and instead inputs a string, Boolean, Array, etc. the function will short circuit and return false instead:

Interrupting a Loop/Function

return can also interrupt a loop and stop execution midway through. Here’s an example:

Even though our for loop can go all the way up to 10, it is interrupted at 3 where it returns and the loop stops executing.

Returning a Function

Finally, you can even return a function from within a function:

This example is a bit more complicated and introduces a JavaScript concept known as closures. If you want to learn more about returning functions, read my previous article: Understand Closures in JavaScript

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

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