How to terminate the class operation in the class constructor

Source: Internet
Author: User
How to terminate the class operation in the class constructor, such as a classclass & nbsp; car & nbsp ;{& nbsp; & nbsp; public & nbsp; $ name; & nbsp; function & nbsp ;__ construct () & nbsp ;{& nbsp; & nb how to terminate class running in class constructor
For example, a class


Class car {

Public $ name;


Function _ construct (){
If ($ name = 'end ')
// Set termination class execution here

}

Function showname (){
Echo 'name is '. $ this-> name;
}

}


Then

$ Aaa = new car ();

$ Aaa-> name = 'test1 ';
$ Aaa-> showname (); // Print name is test1


$ Bbb = new car ();
$ Bbb-> name = 'end ';
$ Bbb-> showname (); // no content should be displayed

Is there any statement like break in a loop that can interrupt the execution of the class, but the statement located before the statement in the constructor can still be executed normally.

------ Solution --------------------
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 ();
------ Solution --------------------
I thought you were about to stop rather than stop the entire operation.
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();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.