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();