简体   繁体   中英

In PHP does return false bubble up?

I have a class with some methods in php.

One public method calls a protected method. If the protected method returns false will the public method return false and not continue?

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. If you don't EXPLICITLY have a return , then there's an implicit 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. return only is in scope of the function/method it is called from.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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