它在嵌套方法中可能的完成方法?

时间:2016-01-04 04:54:00

标签: php

如果字符串不是 hello

,我该如何才能运行代码
class Foo {
    public function simpleMethod($str) {
        if ($str === "hello") {
            $this->bar($str);
            // Its possible dont write here 'return'
        }
        echo "this code always works... but how can i do for that only work if str is not 'hello'";
    }
    private function bar($str) {
        // do awesome stuff...
        // 
        // If this method was called $str should be 'hello'
        // so i want that when this method finish ALL parents method finish too.. 
        // And the next line executed will be '$f->simpleMethod("airport");'
    }
}
$f = new Foo();
$f->simpleMethod("tree");
$f->simpleMethod("hello");
$f->simpleMethod("airport");

2 个答案:

答案 0 :(得分:0)

您需要一个简单的else声明:

public function simpleMethod($str) {
    if ($str === "hello") {
        $this->bar($str);
        // Its possible dont write here 'return'
    } else {
        echo "only get here if str is not 'hello'";
    }
}

答案 1 :(得分:0)

简单,你需要像这样

class Foo {
    public function simpleMethod($str) {
        if ($str === "hello") {
            $this->bar($str);
            // Its possible dont write here 'return'
        }
        else{
         echo "this code always works... but how can i do for that only work if str is not 'hello'";
        }

    }
    private function bar($str) {
        // do awesome stuff...
        // 
        // If this method was called $str should be 'hello'
        // so i want that when this method finish ALL parents method finish too.. 
        // And the next line executed will be '$f->simpleMethod("airport");'
    }
}
$f = new Foo();
//$f->simpleMethod("tree");
$f->simpleMethod("hello");
$f->simpleMethod("airport");