PHP 函数默认返回什么?

发布于 2024-07-30 02:53:36 字数 374 浏览 3 评论 0原文

如果我没有显式返回任何内容,那么 php 函数到底返回什么?

function foo() {}
  1. 它是什么类型?

  2. 它是什么值?

  3. 如何使用 === 精确测试它?

  4. 这是否从 php4 更改为 php5?

  5. function foo() {}function foo() { return; 之间有区别吗? }

(我不是问如何像 if (foo() !=0) ... 那样测试它

If I return nothing explicitly, what does a php function exactly return?

function foo() {}
  1. What type is it?

  2. What value is it?

  3. How do I test for it exactly with === ?

  4. Did this change from php4 to php5?

  5. Is there a difference between function foo() {} and function foo() { return; }

(I am not asking how to test it like if (foo() !=0) ...)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

狼亦尘 2024-08-06 02:53:38

在指定函数返回类型时,我确实发现了一个奇怪的地方。 当你这样做时,你必须明确从你的函数中返回一些东西。

<?php

function errorNoReturnDeclared($a = 10) : ?string {
    if($a == 10) {
        echo 'Hello World!';
    }
}

errorNoReturnDeclared(); //Fatal error

错误:

 Uncaught TypeError: Return value of errorNoReturnDeclared() must be of the type string or null, none returned in 

因此,如果您决定在旧函数上添加一些返回类型规范,请务必考虑这一点。

I did find an oddity when specifying function return types. When you do, you must be explicit about returning something from your functions.

<?php

function errorNoReturnDeclared($a = 10) : ?string {
    if($a == 10) {
        echo 'Hello World!';
    }
}

errorNoReturnDeclared(); //Fatal error

Error:

 Uncaught TypeError: Return value of errorNoReturnDeclared() must be of the type string or null, none returned in 

So if you decide to add some return type specifications on old functions make sure you think about that.

焚却相思 2024-08-06 02:53:38

PHP 函数不返回值与返回 null 的函数具有相同的语义。

function foo() {}

$x=foo();

echo gettype($x)."\n";
echo isset($x)?"true\n":"false\n";
echo is_null($x)?"true\n":"false\n";

这将输出

NULL
false
true

You get the same result if foo is Replaced with

function foo() {return null;}

There has been nochange in this behavior from php4 to php5 to php7 (I just 经过测试可以肯定!)

Not returning a value from a PHP function has the same semantics as a function which returns null.

function foo() {}

$x=foo();

echo gettype($x)."\n";
echo isset($x)?"true\n":"false\n";
echo is_null($x)?"true\n":"false\n";

This will output

NULL
false
true

You get the same result if foo is replaced with

function foo() {return null;}

There has been no change in this behaviour from php4 to php5 to php7 (I just tested to be sure!)

青瓷清茶倾城歌 2024-08-06 02:53:38
  1. null
  2. null
  3. if(foo() === null)
  4. -
  5. 不。

您可以通过执行以下操作来尝试:

$x = foo();
var_dump($x);
  1. null
  2. null
  3. if(foo() === null)
  4. -
  5. Nope.

You can try it out by doing:

$x = foo();
var_dump($x);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文