ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:43:11 24 4
gpt4 key购买 nike

在下面的类(class)中,我需要 kill() 来结束类(class)中发生的一切,并停止类(class)中的所有进程,而不是脚本:

<?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!!!';
?>

最佳答案

正如上面评论中的回答,尝试使用“try”和“catch” block 。

更改“验证”方法

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

关于PHP:停止类执行而不终止脚本(或包含),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14717519/

24 4 0
文章推荐: php - 输出缓冲与将内容存储到 PHP 变量中
文章推荐: php - 当 readyState 为 4 时,为什么我在脚本中调用的 Ajax 函数会连续运行两次?
文章推荐: php - facebook php sdk - 如果用户未授予权限(身份验证失败)则捕获
文章推荐: php - 希腊语日期和时间
可可西里
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com