Home > Backend Development > PHP Tutorial > 怎么在类的构造函数中终止类的运行

怎么在类的构造函数中终止类的运行

WBOY
Release: 2016-06-13 13:17:23
Original
1999 people have browsed it

如何在类的构造函数中终止类的运行
比如一个class


class   car   {

      public   $name;


    function   __construct()   {
        if   ($name= 'end ')
        //这里要设置终止类的执行

    }

    function   showname()   {
          echo   'name   is   '.$this-> name;
    }

}


然后

    $aaa=   new   car();

$aaa-> name= 'test1 ';
$aaa-> showname();   //打印   name   is   test1


$bbb=new   car();
$bbb-> name= 'end ';
$bbb-> showname();     //应该不显示任何内容

请问有没有类似循环中break这样的语句可以打断类的执行,但是在构造函数中位于该语句之前的语句还是能正常执行。

------解决方案--------------------

PHP code


class car  {
    public   $name;
    function   __construct()   {
    }

    public function   showname()   {
        echo   'name   is   '.$this-> name;
    }
    public function setname($name){
        $this->name=$name;
        if ($this->name=='end'){
            exit();
        }
    }

}

$aaa=new car();
$aaa->setname('test1');
$aaa-> showname();


$bbb=new  car();
$bbb->setname('end');
$bbb-> showname();
<br><font color="#e78608">------解决方案--------------------</font><br>想了一下 你是要停止 而不是终止整个运行<br>
Copy after login
PHP code


class car  {
    public   $name;
    protected $goon;
    function   __construct()   {
        $this->goon=true;
    }

    public function   showname()   {
        if ($this->goon==true){
            echo   'name   is   '.$this-> name;
        }
    }
    public function setname($name){
        $this->name=$name;
        if ($this->name=='end'){
            $this->goon=false;
        }
    }

}

$aaa=new car();
$aaa->setname('test1');
$aaa-> showname();


$bbb=new  car();
$bbb->setname('end');
$bbb-> showname();

$bbb=new  car();
$bbb->setname('ttt');
$bbb-> showname(); <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template