简体   繁体   English

这两个功能有什么区别?

[英]what is the difference between these two functions?

what is the difference between these functions ? 这些功能有什么区别? and why we are assigning an empty value to a function parameter ? 为什么我们要为函数参数分配一个空值?

function prints($var = '') {
echo $var; }

function prin($var) {
echo $var; }

Both prints the same result. 两者都打印相同的结果。

what will happen if we assign an empty value to a function parameter ? 如果将空值分配给函数参数会怎样?

The first function has a default value for its first parameter. 第一个函数的第一个参数具有默认值 That means that parameter doesn't need to be specified when calling that function. 这意味着在调用该函数时不需要指定参数。

So you can call the first function without the parameter like this: 因此,您可以在没有参数的情况下调用第一个函数,如下所示:

prints();

And the default value for the first parameter is used. 并且使用第一个参数的默认值。 But when calling the second function the parameter needs to given: 但是在调用第二个函数时,需要给定参数:

prin('parameter');

If you call it without that parameter ( prin() ), you'll get a warning like: 如果在没有该参数( prin() )的情况下调用它,则会收到类似以下的警告:

Warning : Missing argument 1 for prin(), called in … 警告 :缺少prin()的参数1,在…中调用

These functions will work in an identical way will show the same effect, because the default $var = '' is as if you would not assign a default value at all. 这些功能 将以相同的方式工作,并且 将显示相同的效果,因为默认$var = ''就像您根本不会分配默认值一样。

The difference between the two functions, as @Gumbo correctly points out is that prin() can't be called without specifying $var , but prints() can. 正如@Gumbo正确指出的那样,这两个函数之间的区别在于,不指定$var不能调用prin prin() ,但是可以指定prints()

If you call the function with an empty parameter, $var will simply be empty. 如果使用空参数调用该函数,则$var将只是空的。

That's a default parameter 这是默认参数

http://php.net/manual/en/functions.arguments.php http://php.net/manual/en/functions.arguments.php

So for your sample calling prints() will echo an empty string and calling prin() will throw an error because the parameter is missing. 因此,对于您的示例,调用prints()将回显一个空字符串,而调用prin()将抛出错误,因为缺少参数。

The first one has a default value for the variable $var. 第一个变量$ var具有默认值。

You might be interested in reading the PHP manual page on function arguments . 您可能有兴趣阅读有关函数参数的PHP手册页。

The function 功能

function prints($var = '')

receives a default value (which is an empty value in this case). 接收默认值(在这种情况下为空值)。

The other function doesn't receive it. 另一个函数不接收它。 This means, that you can call the first function prints() with no parameter, and it'll treat it as if you called it with an empty string - prints(''). 这意味着,您可以不带参数地调用第一个函数prints(),并且将其视为您使用空字符串调用它时将其视为-prints('')。

You can't call the second function without the defined parameter, as it doesn't set a default value, and will issue an error. 如果没有定义的参数,则无法调用第二个函数,因为它没有设置默认值,并且会发出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM