What Does a PHP Function Return by Default

What does a PHP function return by default?

  1. null
  2. null
  3. if(foo() === null)
  4. -
  5. Nope.

You can try it out by doing:

$x = foo();
var_dump($x);

Do PHP functions need to return a value?

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.

Try

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.

Take a class, for example:

<?php
class Foo
{
private $foo,$bar;
public function __construct()
{
$this->foo = 'bar';
}
public function getFoo()
{
return $this->foo;//<-- getter for private variable
}
public function getBar()
{
return $this->foo;//<-- getter for private variable
}
public function setBar($val = null)
{
$this->bar = $val;
return $this;//<-- return instance for fluent interfacing
}
public function setFoo($val = null)
{
$this->foo = $val;
return $this;
}
}
$f = new Foo();
$f->setFoo('foo')->setBar('bar');//<-- fluent interface
echo $f->getFoo();
?>

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

$f->setFoo('foo');
$f->setBar('Bar');

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

function manipulateArray(array &$arr)//<-- pass by reference
{
sort($arr);
}
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is sorted

as opposed to:

function manipulateArray(array $arr)//<-- pass by copy
{
sort($arr);
return $arr;
}
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is not sorted!
$arr = manipulateArray($arr);//<-- requires reassign

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).



Related Topics



Leave a reply



Submit