简体   繁体   English

在PHP中是否返回假冒气泡?

[英]In PHP does return false bubble up?

I have a class with some methods in php. 我在php中有一些方法的类。

One public method calls a protected method. 一个公共方法称为受保护方法。 If the protected method returns false will the public method return false and not continue? 如果受保护的方法返回false,则公共方法将返回false并且不继续吗?

public static function a() { 
    $class = getClass();
    // some more code...
}

protected static function getClass() {
    $classList = self::find_by_sql("
        SELECT *
          FROM ".self::$table_name."
         WHERE Class_Closed = FALSE
         ORDER BY Start_Date ASC
    ;");

    if (empty($classList)) {
        return false;
    } else {
        return $classList[0];
    }
}

No. return isn't like an exception, and there is no bubbling. 不, return不是例外,也没有冒泡。 If you don't EXPLICITLY have a return , then there's an implicit return null; 如果您没有明确地return null; return ,则隐式return null; :

php > function foo() { }
php > var_dump(foo());
NULL
php > function bar() { $x = 42; }
php > var_dump(bar());
NULL
php > function baz() { return 'hi mom'; }
php > var_dump(baz());
string(6) "hi mom"

This holds true no matter how/where you define the function, including as a class method: 无论您如何/在何处定义函数(包括作为类方法),都适用:

php > class foo { function bar() { } }
php > $foo = new foo();
php > var_dump($foo->bar());
NULL

No. $class will have a false value but you still need to return it from YourClass::a() if you want the method to terminate and return that value immediately. 不会。 $class将具有错误的值,但是如果您希望方法终止并立即返回该值,则仍然需要从YourClass::a()返回它。 return only is in scope of the function/method it is called from. return仅在调用它的函数/方法的范围内。

public static function a(){ 
  $class = getClass();
  if (!$class) {
      return false; // or return $class;
  }
  some more code...
}

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

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