Home >Backend Development >PHP Tutorial >Can a subclass prevent subsequent program execution in the subclass by calling a method in the parent class?
This doubt is caused by the ajaxReturn method in Tp. I also want to learn from this method in other frameworks, but I encountered some problems
<code>class A { public $num = 2; public function return_num() { return $this->num; } } class B extends A{ public function return_A_mum() { $this->return_num(); echo 222; //这里不让他运行 } } $B = new B(); $a = $B->return_A_mum(); echo $a; /* 这里输出$a是222; */ </code>
Students who have used tp
all know that $this->ajaxReturn
does not need to be preceded by return
, but if my code wants to return the num
value in the A
class, it must be in Class A calls the return_num
method of class B with return
in front of it. How does TP
do it? The subclass calls the method in the parent class to obtain the data and stop the execution of the subsequent code of the subclass?
This doubt is caused by the ajaxReturn method in Tp. I also want to learn from this method in other frameworks, but I encountered some problems
<code>class A { public $num = 2; public function return_num() { return $this->num; } } class B extends A{ public function return_A_mum() { $this->return_num(); echo 222; //这里不让他运行 } } $B = new B(); $a = $B->return_A_mum(); echo $a; /* 这里输出$a是222; */ </code>
Students who have used tp
all know that $this->ajaxReturn
does not need to be preceded by return
, but if my code wants to return the num
value in the A
class, it must be in Class A calls the return_num
method of class B with return
in front of it. How does TP
do it? The subclass calls the method in the parent class to obtain the data and stop the execution of the subsequent code of the subclass?
Because the method you call has exit, die and other methods...
Some specific outputs have format requirements, so such methods often have built-in exit, such as json, xml, etc. The most common one is url jump. Yes, you must exit after using the header function to send a jump instruction, otherwise a lot of output will be produced later.
It seems that Yii, a very unique framework, has two methods: $controller->redirect() and $controller->redirectAndExit(). People who don’t know will die miserably if they call the former.
What you are doing is returning json. If you do not return it, it is likely that extra characters will be added after json, causing the data format to be illegal.
You can find out this problem by looking at the source code of thinkphp.
<code class="php">protected function ajaxReturn($data) { // 返回JSON数据格式到客户端 包含状态信息 header('Content-Type:application/json; charset=utf-8'); exit(json_encode($data)); }</code>
<code>class A { public $num = 2; public function return_num() { return $this->num; } } class B extends A { public function return_A_mum(&$data) { $data = $this->return_num(); } } $B = new B(); $B->return_A_mum($a); echo $a;</code>
Output 2
See if it is the effect you want