Php return default value

Возврат значений

Значения возвращаются при помощи необязательного оператора возврата. Возвращаемые значения могут быть любого типа, в том числе это могут быть массивы и объекты. Возврат приводит к завершению выполнения функции и передаче управления обратно к той строке кода, в которой данная функция была вызвана. Для получения более детальной информации ознакомьтесь с описанием return .

Замечание:

Если конструкция return не указана, то функция вернет значение NULL .

Использование выражения return

Пример #1 Использование конструкции return

Функция не может возвращать несколько значений, но аналогичного результата можно добиться, возвращая массив.

Пример #2 Возврат нескольких значений в виде массива

function small_numbers ()
return array ( 0 , 1 , 2 );
>
list ( $zero , $one , $two ) = small_numbers ();
?>

Для того, чтобы функция возвращала результат по ссылке, вам необходимо использовать оператор & и при описании функции, и при присвоении переменной возвращаемого значения:

Пример #3 Возврат результата по ссылке

Для получения более детальной информации о ссылках обратитесь к разделу документации Подробно о ссылках.

Объявление типов возвращаемых значений

В PHP 7 добавлена возможность объявлять тип возвращаемого значения. Аналогично объявлению типов аргументов можно задать тип значения, которое будет возвращаться функцией. Типы, которые можно объявить для возвращаемых значений те же, что и для аргументов фукнций.

Режим строгой типизации также работает для объявлении типа возвращаемого значения. В обычном режиме слабой типизации возвращаемое из функции значение приводится к корректному типу. При строгой типизации возвращаемое значение должно быть заданного типа, иначе будет выброшено исключение TypeError.

Замечание:

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

Примеры

Пример #4 Обычное объявление типа возвращаемого значения

// Будет возвращаться значение типа float.
var_dump ( sum ( 1 , 2 ));
?>

Результат выполнения данного примера:

Пример #5 То же в режиме строгой типизации

function sum ( $a , $b ): int return $a + $b ;
>

var_dump ( sum ( 1 , 2 ));
var_dump ( sum ( 1 , 2.5 ));
?>

Результат выполнения данного примера:

int(3) Fatal error: Uncaught TypeError: Return value of sum() must be of the type integer, float returned in - on line 5 in -:5 Stack trace: #0 -(9): sum(1, 2.5) #1 thrown in - on line 5

Пример #6 Возврат объектов

function getC (): C return new C ;
>

Результат выполнения данного примера:

Источник

What Does a PHP Function Return by Default

PHP functions do not need to return anything, and I doubt it would negatively affect the performance if you didn’t return anything. If anything, it would positively affect the performance.

php function return 0 or no return at all

Just to clarify: For cleaner and more understandable code, you should always return something, if the function is not a void function. You have to ask yourself the question:

  • Why is the function not returning the desired result?
  • What should be returned in an error case?
  • Is it specified, when the function behaves different?
  • How can the caller react, if the result is unexpected.

For the last point it is necassary, that you can clearly see, what is the error value, for example by explicit add an return null; after your loop.

A good way to force you to think about your functions is to write Documentation like, PHPDoc

Why does my PHP function return 1 or nothing instead of true or false?

Your function doesn’t return 1 or nothing, it is the echo that decides to render the result that way.

var_dump(isPalindrome("A nut for a jar of tuna"));

if (isPalindrome("A nut for a jar of tuna") === true) echo 'true';
> else echo 'false';
>

to get some more debug friendly output

Why we should always return values from a function?

A function needn’t return anything. If you look at C(++) function, many of them don’t (well, not explicitly):

void nonReturningFunction(const int *someParam);
int main()
int i = 12;
nonReturningFunction(&i);
return 0;
>
void nonReturningFunction(const int *someParam)
printf("I print the value of a parameter: %d",someParam);
>

The latter returns nothing, well, it returns a void. The main function does return something: 0 , this is generally a signal to the system to let it know the programme is finished, and it finished well.

The same logic applies to PHP, or any other programming language. Some functions’ return value is relevant, another function may not be required to return anything. In general functions return values because they are relevant to the flow of your programme.

 class Foo 
private $foo,$bar;
public function __construct()
$this->foo = 'bar';
>
public function getFoo()
return $this->foo;// >
public function getBar()
return $this->foo;// >
public function setBar($val = null)
$this->bar = $val;
return $this;// >
public function setFoo($val = null)
$this->foo = $val;
return $this;
>
>
$f = new Foo();
$f->setFoo('foo')->setBar('bar');// echo $f->getFoo();
?>

If the setter function didn’t return anything, you’d have to write:

So in this case, return values are relevant. Another example where they’re irrelevant:

function manipulateArray(array &$arr)// sort($arr);
>
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is sorted
function manipulateArray(array $arr)// sort($arr); 
return $arr;
>
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is not sorted!
$arr = manipulateArray($arr);//

Passing by reference is deemed risky in many cases, that’s why the latter approach is generally considered to be better. So in many cases the functions needn’t return a value, but they do all the same because it makes the code safer overall.
That might be why you’re under the impression that functions must always return a value.

PHP object default return value

You need to add actual functionality to the object to achieve this. Simply casting an array to an object only creates an object that holds some values, it is not very different from an array. There’s no notion of «default values» for either arrays or objects, the only way to simulate this concept is by implementing it using magic methods, in this case __toString . As such, you need to create a class akin to this:

class ObjectWithDefaultValue public function __construct($params) // assign params to properties 
.
>

public function __toString() return $this->obj1;
>
>

function sth() $obj = new ObjectWithDefaultValue(array(
"obj1" => $obj1,
"obj2" => $obj2,
"obj3" => $obj3
));

return $obj;
>

$obj = sth();
echo $obj;

Return in a function — PHP

return as the word itself says returns (gives back) something.

In this case either $var1 + $var2 or $var1 — $var2 .

Variables inside of a function can’t usually be accessed outside of it.

With return however you can get something from inside a function to use it oustide of it.

Keep in mind, that a return will end the execution of a function.

Return by reference in PHP

Suppose you have this class:

class Fruit private $color = "red";

public function getColor() return $this->color;
>

public function &getColorByRef() return $this->color;
>
>

The class has a private property and two methods that let you access it. One returns by value (default behavior) and the other by reference. The difference between the two is that:

  • When using the first method, you can make changes to the returned value and those changes will not be reflected inside the private property of Fruit because you are actually modifying a copy of the property’s value.
  • When using the second method, you are in fact getting back an alias for Fruit::$color — a different name by which you refer to the same variable. So if you do anything with it (including modifying its contents) you are in fact directly performing the same action on the value of the property.

Here’s some code to test it:

echo "\nTEST RUN 1:\n\n";
$fruit = new Fruit;
$color = $fruit->getColor();
echo "Fruit's color is $color\n";
$color = "green"; // does nothing, but bear with me
$color = $fruit->getColor();
echo "Fruit's color is $color\n";

echo "\nTEST RUN 2:\n\n";
$fruit = new Fruit;
$color = &$fruit->getColorByRef(); // also need to put & here
echo "Fruit's color is $color\n";
$color = "green"; // now this changes the actual property of $fruit
$color = $fruit->getColor();
echo "Fruit's color is $color\n";

See it in action.

Warning: I feel obliged to mention that references, while they do have legitimate uses, are one of those features that should be used only rarely and only if you have carefully considered any alternatives first. Less experienced programmers tend to overuse references because they see that they can help them solve a particular problem without at the same time seeing the disadvantages of using references (as an advanced feature, its nuances are far from obvious).

Источник

Functions in PHP: Return Values and Parameters

Monty Shokeen

Monty Shokeen Last updated Feb 17, 2021

Functions are an important part of programming languages. They help us avoid code duplication by allowing us to run the same set of instructions over and over again on different data.

In this tutorial, we will talk about functions in PHP. We will cover all the basic concepts of functions in PHP, and you’ll learn how to create your own user-defined functions in PHP. You will learn about returning values from a function and function parameters in PHP. You’ll also learn other concepts like setting default argument values or passing an argument by reference.

Internal Functions in PHP

PHP comes with a lot of built-in functions that you can use in your program. Some of these functions come as standard, while others become available to you through specific PHP extensions.

PHP comes with a lot of functions to work with strings. For example, you can use the str_contains() function to check if a string contains a substring and the wordwrap() function to wrap a string to a given number of characters. These functions are available for you to use as standard.

Another set of PHP functions for manipulating images is available if you install the GD extension library. Once the extension is enabled, you will be able to use functions like imagecreatetruecolor() , imagecreatefrompng() , and imagefill() to create and manipulate images.

If you ever get a fatal undefined function error in PHP but you are certain that it is an internal function, make sure that you have installed the respective extensions to use that function.

User-Defined Functions in PHP

You can also define your own functions in PHP. Defining your own functions becomes a necessity in almost every non-trivial program you write. They are a great way to avoid code duplication and errors.

Here is some basic code to define a function that outputs a greeting when we call the function later.

Источник

Читайте также:  Javascript array join two arrays
Оцените статью