PHP:停止类执行而不终止脚本(或包括)

时间:2013-02-05 21:44:32

标签: php class

在下面的类中,我需要kill()来结束类中正在发生的事情,并且只停止所有和任何进程在类中,而不是脚本:

<?php
class email {
    //Expressions
    const exp_name      = "/^[A-Za-z .'-]+$/";
    const exp_email     = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    const error         = "We are sorry, but there appears to be a problem with the form you submitted.<br/>";
    private $msg        = 'Thank you for subscribing';
    protected $status   = true;


    function __construct() {
        self::validate();
        echo '<br/>the CLASS continued</b><br/>';
    }


    private function validate() {
        //Empty fields
        foreach ($_REQUEST as $key => $value) {
            $val = str_replace( ' ', '', $value );
            if ( $val === '' ) {
                self::error( 'empty', $key );
                self::kill(); //If empty, this should end the loop and class
            } //if:empty
        } //foreach


        //Validate Name
        if( !preg_match(self::exp_name,$_POST['Name']) ) {
            self::error( 'name' );
            self::kill(); //kill


        //Validate e-Mail
        if( !preg_match(self::exp_email,$_POST['e-Mail']) ) {
            self::error( 'email' );
            self::kill(); //kill
        }
  }


    public function status() {
        return $this->status;
    }

    public function msg() {
        return $this->msg;
    }


    private function error( $type = null, $value = null ) {
        switch( $type ) {
            case 'empty':
            $this->msg = self::error . "<div class='error'><b>The following field is empty: </b>" . $value . "</div>";
            self::set( false );
            break;

            case 'name':
            $this->msg = self::error . "<div class='error'><b>The First Name you entered does not appear to be valid.</b></div>";
            self::set( false );
            break;

            case 'email':
            $this->msg = self::error . "<div class='error'><b>The e-Mail you entered does not appear to be valid.</b></div>";
            self::set( false );
            break;

            default:
            self::set( false );
            $this->msg = self::error;
        }
    return; //kill app
    }


    private function set( $boolean = false ) {
        $this->status = $boolean;
    }


    private function kill() {
        //die();
        //exit( $this );
        //exit();
        //return;
        //break;
    }
}


$email = new email();
echo $email->msg();
echo '<br/>';
echo '<br/>';
echo 'The script continued!!!';
?>

6 个答案:

答案 0 :(得分:10)

如上文评论中所述,尝试使用“try”和“catch”块。

更改“验证”方法

private function valdidate( $type = null, $value = null ) {
    // Anything that is going wrong:
    throw new Exception("Your error message");
}

课外:

try {
      $mail = new email();
} catch (Exception $e) {
      echo $e->getMessage(); // Handle the message properly here.
}

有关异常的更多信息,请参阅:

http://php.net/manual/en/language.exceptions.php

答案 1 :(得分:1)

而不是self::kill();只需使用return;

如果您需要kill执行其他操作,只需在需要呼叫时使用return self::kill();并将kill更改为:

private function kill() {
    doStuff();
    return;
}

答案 2 :(得分:0)

没有人阻止你在validate方法上返回布尔值,然后设置一个简单的if / else块来评估其结果。

private function validate() {
    //Empty fields
    foreach ($_REQUEST as $key => $value) {
        $val = str_replace( ' ', '', $value );
        if ( $val === '' ) {
            // You shouldn't call staticaly 
            // self::error( 'empty', $key );
            $this->error('empty', $key);
            // self::kill(); //If empty, this should end the loop and class
            return false;
        } //if:empty
    } //foreach


    //Validate Name
    if( !preg_match(self::exp_name,$_POST['Name']) ) {
        $this->error( 'name' );
        return false;
    }

    //Validate e-Mail
    if( !preg_match(self::exp_email,$_POST['e-Mail']) ) {
        $this->error( 'email' );
        return false;
    }

    return true;
}

然后在构造函数中:

if ($this->validate()) {
    echo '<br/>the CLASS continued</b><br/>';
}

答案 3 :(得分:0)

如果我理解正确,则kill()可以使用return false。据我所知,返回会“抛出”你的方法,并且执行不会受到任何影响。如果我不能正确理解你的问题,那就不会有任何影响。

最诚挚的问候!

答案 4 :(得分:0)

问题在于课堂上没有'杀我'选项。 PHP使用unset方法来销毁变量,并且无法从类中调用。正如手册所述'从PHP 5开始,不可能在对象方法中取消$ this',所以你不能杀掉你的类。

话虽如此,你会怎么做才能确保在没有验证时没有任何反应?确保检查不应该继续出错的类的每个方法中的状态。您将在下面找到更改的代码以显示此过程。请务必阅读有关我为何做某事的评论。

<?php
class email {
    //Expressions
    const exp_name      = "/^[A-Za-z .'-]+$/";
    const exp_email     = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    const error         = "We are sorry, but there appears to be a problem with the form you submitted.<br/>";
    private $msg        = 'Thank you for subscribing';
    protected $status   = true;


    function __construct() {
        //first check if it validates.
        //if it doesnt, end the constructor so the "class continued" line won't show.
        if (!self::validate()) {
            return;
        }


        echo '<br/>the CLASS continued</b><br/>';
    }


    private function validate() {
        //have the validate method return true/false.
        //Now you can use the output of this method to stop the script if needed

        //Empty fields
        foreach ($_REQUEST as $key => $value) {
            $val = str_replace( ' ', '', $value );
            if ( $val === '' ) {
                self::error( 'empty', $key );
                return false; //just return false when it doesnt validate
            } //if:empty
        } //foreach


        //Validate Name
        if( !preg_match(self::exp_name,$_POST['Name']) ) {
            self::error( 'name' );
            return false; //just return false when it doesnt validate
        }

        //Validate e-Mail
        if( !preg_match(self::exp_email,$_POST['e-Mail']) ) {
            self::error( 'email' );
            return false; //just return false when it doesnt validate
        }

        //else return true
        return true;
    }

    public function status() {
        //always allow the script to return the status
        return $this->status;
    }

    public function msg() { 
        //always allow the script to return the error message
        return $this->msg;
    }

    //example function on how to make sure nothing happens on error
    public function send() {    
        //return false on error so the rest method is not executed
        if ($this->status!==true)
            return false;

        //else continue
        echo "I'm sending an email!";
        //mail(.....)
    }


    private function error( $type = null, $value = null ) {     
        //you set the status to false here, so you can use it to check if an error occured
        //since you always set it to false, remove it from the switch statement. 
        //This way there is less duplicate code and thus less chance for errors

        self::set( false );

        switch( $type ) {
            case 'empty':
                $this->msg = self::error . "<div class='error'><b>The following field is empty: </b>" . $value . "</div>";
                break;

            case 'name':
                $this->msg = self::error . "<div class='error'><b>The First Name you entered does not appear to be valid.</b></div>";
                break;

            case 'email':
                $this->msg = self::error . "<div class='error'><b>The e-Mail you entered does not appear to be valid.</b></div>";
                break;

            default:
                $this->msg = self::error;
        }

        return;
    }


    private function set( $boolean = false ) {
        //use a check to set the value to make sure its always a boolean
        //this way it will be false unless you actually set it to true.
        $this->status = ($boolean===true);
    }
}


$email = new email();

//now you can do a check for the message and only continue if there was no error
if ($email->status() !== false) {
    //Do whatever you want with the e-mail
    $email->send();
    echo 'An e-mail has been sent!';
} else {
    echo 'Something was wrong with the email ('.$email->msg().')';
}

//or another approach could be to directly send it and catch if there was an error
//make sure to check for false with === to be sure its realy a boolean. 
//If you would just check with == the method would also fail if the send() method would return 0 for instance
if ($email->send() === false) {
    echo 'Something was wrong with the email ('.$email->msg().')';
}

//but no matter what, the script will continue
echo '<br/>';
echo '<br/>';
echo 'And the script continued!!!';
?>

答案 5 :(得分:0)

你可以这样编程:

class email {
    //Expressions
    public static $errorOccuredInCurrentRun = false;

    const exp_name = "/^[A-Za-z .'-]+$/";
    const exp_email = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    const error = "We are sorry, but there appears to be a problem with the form you submitted.<br/>";

    private $msg = 'Thank you for subscribing';
    protected $status = true;

    public static function factory(){
        //du your validation
        self::$errorOccuredInCurrentRun = false;
        self::validate();
        if(!self::$errorOccuredInCurrentRun){
            return new Email();
        }else{
            return null;
        }
    }

    private function __construct() {
        echo '<br/>the CLASS continued</b><br/>';
    }

    private static function validate() {
        //Empty fields
        foreach ($_REQUEST as $key => $value) {
            if(self::$errorOccuredInCurrentRun){
                break;
            }
            $val = str_replace(' ', '', $value);
            if ($val === '') {
                self::error('empty', $key);
                self::kill(); //If empty, this should end the loop and class
            } //if:empty
        } //foreach
        //Validate Name
        if(self::$errorOccuredInCurrentRun){
            if (!preg_match(self::exp_name, $_POST['Name'])) {
                self::error('name');
                self::kill(); //kill
                //Validate e-Mail
                if(self::$errorOccuredInCurrentRun){
                    if (!preg_match(self::exp_email, $_POST['e-Mail'])) {
                        self::error('email');
                        self::kill(); //kill
                    }
                }
            }
        }
    }

    public function status() {
        return $this->status;
    }

    public function msg() {
        return $this->msg;
    }

    private function error($type = null, $value = null) {
        switch ($type) {
            case 'empty':
                $this->msg = self::error . "<div class='error'><b>The following field is empty: </b>" . $value . "</div>";
                self::set(false);
                break;

            case 'name':
                $this->msg = self::error . "<div class='error'><b>The First Name you entered does not appear to be valid.</b></div>";
                self::set(false);
                break;

            case 'email':
                $this->msg = self::error . "<div class='error'><b>The e-Mail you entered does not appear to be valid.</b></div>";
                self::set(false);
                break;

            default:
                self::set(false);
                $this->msg = self::error;
        }
        return; //kill app
    }

    private function set($boolean = false) {
        $this->status = $boolean;
    }

    private function kill() {
        self::$validationRunCompleted;
    }

}

然后像这样使用它:

$email = email::factory();
if(is_null($email)){
    //something went wrong
}else{
    //validation was fine
}

如果当前“运行”没有任何错误,我只执行一些东西。只有在没有错误的情况下,您才能获得电子邮件对象本身以及您可以继续执行的操作