如果变量具有特定值,则中断

I try to listen for the value of a variable and execute some code if it has a specific value.

e.g. I execute the function element() inside a switch statement and I have to execute break if the value of $element is false.

At the moment I do it like this:

switch(strtolower($testcase)) {
    case 'test':
        $element = $sel->element("class name", "btn-primary", true);
        if ($element == false) { break; }
        $element->click("");
...

public function element($using, $value, $takeScreenshot=false, $customMessage="")
{   
    try {
        $element = $this->driver->element($using, $value);

    } catch(PHPWebDriver_UnhandledWebDriverError $exception) {

        $msg = "<b>PHPWebDriver_UnhandledWebDriverError: $using</b> is "
                . "not a valid value for the parameter <b>\$using</b>!";

        if ($customMessage !== "") {
            $msg = "<b>$customMessage</b><br>$msg";
        }

        $this->setMessage(1, $msg, $exception, $takeScreenshot, $value);
        return false;

    } catch(PHPWebDriver_NoSuchElementWebDriverError $exception) {
        $msg = "<b>PHPWebDriver_NoSuchElementWebDriverError:</b> No "
                . "Element with <b>'$using'</b> and value <b>'$value'</b> found !";

        if ($customMessage !== "") {
            $msg = "<b>$customMessage</b><br>$msg";
        }

        $this->setMessage(1, $msg, $exception, $takeScreenshot, $value);
        return false;
    }

    return $element;
}

But I would like to simplify it so that the line if ($element == false) { break; } is not needed anymore. e.g.

switch(strtolower($testcase)) {
    case 'test':
        $element = $this->element("class name", "btn-primary", true);
        $element->click("");
...

I tried to return break; but this failed. Is there another way? e.g. can I add an EventListener which executes break automatically in the switch case if the value of $element is false?

When building functions, it's usually best to design them to be de-coupled, not coupled. This means, element() shouldn't care about what is calling it.

Therefore, attempting to break a switch from within element() would be a bad programming design.

If element() should always stop execution when it hits a certain spot, regardless of what called it, you should consider throwing an exception. However, this won't simplify the code in your switch statement as you'd have to use try, catch blocks.

With that said, since PHP allows assignments in conditionals, you could simplify the code you have written as:

    if ($element = $sel->element("class name", "btn-primary", true)) {
         $element->click("");
    }