函数不需要返回任何内容...如果您查看 C(++) 函数,您会发现其中许多函数不需要返回任何内容(好吧,不是明确地):
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);
}
后者什么也不返回,好吧,它返回一个空值。 main 函数确实返回了一些东西:0
,这通常是向系统发出的信号,让其知道程序已完成,并且完成得很好。
同样的逻辑也适用于 PHP 或任何其他编程语言。某些函数的返回值是相关的,而另一个函数可能不需要返回任何内容。一般来说,函数会返回值,因为它们与程序的流程相关。
以一堂课为例:
<?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();
?>
如果 setter 函数没有返回任何内容,则必须编写:
$f->setFoo('foo');
$f->setBar('Bar');
因此在这种情况下,返回值是相关的。另一个例子,它们是无关紧要的:
function manipulateArray(array &$arr)//<-- pass by reference
{
sort($arr);
}
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is sorted
与以下相反:
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
在许多情况下,通过引用传递被认为是有风险的,这就是为什么后一种方法通常被认为更好的原因。因此,在许多情况下,函数不需要返回值,但它们的作用都是相同的,因为这使代码整体上更安全。
这可能就是为什么您认为函数必须always返回一个值。