7

以下のクラスでは、クラス内で起こっていることをすべて終了し、スクリプトではなくクラス内のすべてのプロセスを停止するために 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!!!';
?>
4

6 に答える 6

12

上記のコメントで回答したように、「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

于 2013-02-05T23:46:54.637 に答える
2

self::kill();単に使用する代わりにreturn;

kill他のことをする必要がある場合return self::kill();は、呼び出す必要があるときにいつでも使用して、次のように変更killします。

private function kill() {
    doStuff();
    return;
}
于 2013-03-18T16:08:11.923 に答える
1

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/>';
}
于 2013-03-19T17:36:13.443 に答える
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
}

現在の「実行」にエラーがなかった場合にのみ実行します。そして、エラーがなかった場合にのみ、あなたはあなたが続けることができそしてあなたが必要とすることをすることができるもので電子メールオブジェクト自体を手に入れます

于 2013-03-21T17:28:51.057 に答える
0

私がこれを正しく理解していれば、代わりにkill()を使用できますreturn false。私が知る限り、return はメソッドの外に「スロー」し、実行はまったく影響を受けません。問題を正しく理解していなかったら申し訳ありません。

よろしくお願いします!

于 2013-03-20T15:15:09.227 に答える
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!!!';
?>
于 2013-03-21T08:20:24.623 に答える