This article analyzes the PHP object-oriented programming method with examples. Share it with everyone for your reference, the details are as follows:
In the development process of very large projects, if you use process-oriented development, the amount of code will be very large, which will use a lot of judgment and loop nesting, and a lot of very similar code, not only will the project code The volume is even larger, which is not conducive to development, reuse and maintenance.
Object-oriented can solve this problem very well. Object-oriented has good encapsulation and saves a lot of energy. You don’t need to care about the internal operation of the object. You only need to care about the interaction between objects, which is easy to maintain, and inheritance The code is greatly streamlined.
Let’s look at a topic first:
Example: Zhang San is an ordinary person. When others greet him in the morning, he will say "good morning". But one day he was hit by a car and suffered a little brain injury. Therefore, when others greet him in the morning, he will say "good morning". , he sometimes said: "Good morning", but sometimes said: "Good evening", and even insulted the other party.
Analysis: Since we are now object-oriented, let’s take out the objects first
Object 1: Zhang San (person) IQ (name is attribute) Say hello (verb is method)
Object 2: The car hit someone (the verb is the method)
<?php //创建一个human类,类是对象的实例(工厂里的模子) class human{ //普通人的iq为100 public $iq = 100; //打招呼,早上看到人就早上好 public function greet(){ echo '早上好'; } } //实例化一个对象李四 $lisi = new human(); $lisi->greet(); //返回早上好 ?>
This is to instantiate a normal John Doe
Let’s take a look at Li Si who was hit by a car
<?php //创建一个human类,类是对象的实例(工厂里的模子) class human{ //普通人的iq为100 public $iq = 100; //打招呼,早上看到人就早上好 public function greet(){ //当智商大于等于100 if($this->iq>=100){ echo '早上好','<br />'; }else{ //当智商小于100,随机出现以下问候 $regard = array('早上好','晚上好','混蛋'); echo $regard[rand(0,2)],'<br />'; } } } //实例化一个对象李四 $lisi = new human(); $lisi->greet(); //返回早上好 class car{ public function hit($people){ //撞了以后人的智商随机出现了变化 $people->iq=rand(40,120); } } //实例化一辆宝马车子 $baoma = new car(); //宝马车子撞人了 $baoma->hit($lisi); //撞人之后人的智商 echo $lisi->iq,'<br />'; //人的根据智商的多少,问候也不相同 $lisi->greet(); ?>
Readers who are interested in more object-oriented content related to PHP can check out the special topic of this site: "Introduction Tutorial on PHP Object-Oriented Programming"
I hope this article will be helpful to everyone in PHP programming.