2016/3/22 面向过程 面向对象:①多态 ②引入页面加载类

面向过程:每一步骤,步步推进,重复使用性差。

面向对象:封装(class类,function方法,new初始化),重复使用性强。

 例子:

 1 //面向过程
 2 $r1=20;
 3 $r2=10;
 4 $mj=3.14*$r1*$r1-3.14*$r2*$r2;
 5 echo $mj;
 6 
 7 //面向对象
 8 class yuan
 9 {
10     private $r;
11     function __construct($r)
12     {
13         $this->r=$r;
14     }
15     function mj()
16     {
17         return 3.14*$this->r*$this->r;
18     }
19 }
20 $yuan1=new yuan(10);
21 $yuan2=new yuan(20);
22 echo $yuan2->mj()-$yuan1->mj();

①多态:父类引用指向子类实例,由于子类的不同,所表现出的差别,就是多态。
注意:
1,Java中多态的实现方式:接口实现,继承父类进行方法重写,同一个类中进行方法重载。
2,子类继承父类方法是重写。类不同。
3,同一类中类型不同,数量不同,是方法的重载。

例:

 1 class Ren
 2 {
 3     public $name;
 4     public $age=10;
 5     
 6     public function Say()
 7     {
 8 
 9     echo $this->name."正在说";
10     }
11     function __construct($n)
12     {
13         $this->name=$n;
14     }
15     function __tostring()
16     {
17         return "成员变量name的值为:".$this->name."<br>"."成员方法Say()的作用是...";
18     }
19     function __clone()    //克隆的方法
20     {
21         $this->age=20;//$this找的是复本
22         //$that->aa=16;//$that找的是原本,老版本中有,新版本中已弃用。
23     }
24 
25     
26 }
27 $ren=new Ren("aa");
28 $r2=clone $ren; //克隆 $ren  
29 echo $r2; 

30 var_dump($ren);

31 var_dump($r2);

显示效果:

继承中的重写

 1 class Ren
 2 {
 3     public $name;
 4     public $age=10;
 5     
 6     public function Say()
 7     {
 8 
 9         echo $this->name."正在说";
10     }
11     function __construct($n)
12     {
13         $this->name=$n;
14     }
15     function __tostring()
16     {
17         return "成员变量name的值为:".$this->name."<br>"."成员方法Say()的作用是...";
18     }
19     function __clone()
20     {
21         $this->age=20;//$this找的是复本
22         $that->aa=16;//$that找的是原本,老版本中有,新版本中已弃用。
23     }
24 
25     
26 }
27 
28 class China extends Ren
29     {
30         public function Say()
31         {
32             echo "你好!";
33         }
34     }
35 $ren=new China("hello");
36 $ren->Say();
37 echo $ren->name;

显示效果:

② 引入  

方式:

相对路径:从当前文件找到另一个文件路径。

include("文件名.php");//同级目录下

include"../文件名.php";  //上级目录

require_once("文件名.php");//同级目录下

require_once"文件夹名/class.php";//下级目录

自动加载类

1 function __autoload($classname)
2 {
3     require_once"class_".$classname.".php";
4 }

例子:

1 include("text6.php");
2 $test=new Text();
3 var_dump($test);
4 $test->run();

显示效果:

原文地址:https://www.cnblogs.com/haodayikeshu/p/5305733.html