Home > headlines > body text

Comprehensively guide you to understand and learn the three basic features of PHP object-oriented encapsulation, inheritance, and polymorphism

伊谢尔伦
Release: 2017-07-05 09:26:42
Original
2580 people have browsed it

Object-oriented programming (OOP) is a basic skill for our programming, and PHP5 provides good support for OOP. How to use OOP ideas to perform advanced programming of PHP is very meaningful for improving PHP programming capabilities and planning a good Web development architecture.

When we usually build a website with a database backend, we will consider that the program needs to be suitable for different application environments. What is different from other programming languages ​​is that in PHP, a series of specific functions are used to operate the database (if you do not use the ODBC interface). Although this is very efficient, the encapsulation is not enough. If there is a unified database interface, then we can apply it to a variety of databases without making any modifications to the program, thus greatly improving the portability and cross-platform capabilities of the program.

Now our php Chinese website will give you a comprehensive understanding of the three basic features of php object-oriented: encapsulation, inheritance, and polymorphism.

You can watch the relevant video courses on our php Chinese website: Chapter 10 Classes and Objects in PHP In-depth lecture: This time it must be If you want to understand

, you can also read the PHP Chinese manual:Tutorial on classes and objects

The three major characteristics of PHP object-oriented: inheritance, encapsulation, polymorphism

The so-called encapsulation, also It is to encapsulate objective things into abstract classes, and the class can only allow trusted classes or objects to operate its own data and methods, and hide information from untrustworthy ones.

Encapsulation is one of the characteristics of object-oriented and the main characteristic of object and class concepts. Simply put, a class is a logical entity that encapsulates data and code that operates on these data. Within an object, some code or some data can be private and cannot be accessed by the outside world. In this way, objects provide varying levels of protection for internal data to prevent unrelated parts of the program from accidentally changing or incorrectly using the private parts of the object.

The so-called inheritance refers to a method that allows an object of a certain type to obtain the properties of an object of another type. It supports the concept of hierarchical classification.

Inheritance refers to the ability to use all the functionality of an existing class and extend these functionality without rewriting the original class. The new class created through inheritance is called a "subclass" or "derived class", and the inherited class is called a "base class", "parent class" or "super class". The process of inheritance is the process from general to special. To achieve inheritance, you can achieve it through "Inheritance" and "Composition". There are two types of ways to implement the concept of inheritance: implementation inheritance and interface inheritance. Implementation inheritance refers to the ability to directly use the properties and methods of the base class without additional coding; interface inheritance refers to the ability to use only the names of properties and methods, but subclasses must provide implementations;

The so-called polymorphism means that the same method of a class instance has different manifestations in different situations.

Polymorphism allows objects with different internal structures to share the same external interface. This means that although the specific operations on different objects are different, they (those operations) can be called in the same way through a common class.

1. Inheritance

1. How to implement inheritance?

Use the extends keyword for the subclass to let the subclass inherit the parent class;

class Student extends Person{}

2. Things to note when implementing inheritance?

① Subclasses can only inherit non-private properties of the parent class.

②After a subclass inherits a parent class, it is equivalent to copying the

attributes and methods of the parent class to the subclass, which can be called directly using $this.

③ PHP only supports single inheritance and does not support one class inheriting multiple classes. But a class carries out multi-level inheritance;

class Person{}

class Chengnian extends Person{}

class Student extends Chengnian{}

//Student类就同时具有了Chengnian类和Person类的属性和方法
Copy after login

3. Method overwriting (method rewriting)

Conditions ① The subclass inherits the parent class.

Condition ② The subclass overrides the existing method of the parent class.

Meeting the above two conditions is called method coverage. After overriding, when a subclass calls a method, the subclass's own method will be called.

Similarly, in addition to method overrides, subclasses can also have attributes with the same name as the parent class for attribute overrides.

4、如果,子类重写了父类方法,如何在子类中调用父类同名方法?

partent::方法名();

所以,当子类继承父类时,需在子类的构造中的第一步,首先调用父类构造进行复制。

function construct($name,$sex,$school){

  parent::construct($name,$sex);

  $this->school = $school;

}
Copy after login

实例一枚:

class Student extends Person{      //子类继承父类
  public $school;           function construct($name,$sex,$school){   //子类的构造函数
   parent::construct($name,$sex);  //调用父类构造进行复制
   $this->school = $school;
  }
  
  function program(){
   echo "PHP真好玩!我爱PHP!PHP是世界上最好用的编程语言!<br>";
  }
  
  function say(){
   parent::say();      //重写父类的同名方法
   echo "我是{$this->school}的";
  }
 }
 
 $zhangsan = new Student("张三","男","起航");
 $zhangsan->say();
 $zhangsan->program();
Copy after login

二、封装

1、什么是封装?

通过访问修饰符,将类中不需要外部访问的属性和方法进行私有化处理,以实现访问控制

【注意】:是实现访问控制,而不是拒绝访问。 也就是说,我们私有化属性之后,需要提供对应的方法,让用户通过我们提供的方法处理属性。

2、封装的作用?

①使用者只关心类能够提供的功能,而不必关心功能实现的细节!(封装方法)

②对用户的数据进行控制,防止设置不合法数据,控制返回给用户的数据(属性封装+set/get方法)

3、实现封装操作?

① 方法的封装

对于一些只在类内部使用的方法,而不像对外部提供使用。那么,这样的方法我们可以使用private进行私有化处理。
private function formatName(){} //这个方法仅仅能在类内部使用$this调用
function showName(){
$this -> formatName();
}

②属性的封装+set/get方法

为了控制属性的设置以及读取,可以将属性进行私有化处理,并要求用户通过我们提供的set/get方法进行设置
private $age;
function setAge($age){
$this->age = $age;
}
function getAge(){
return $this->age;
}
$对象 -> getAge();
$对象 -> setAge(12);

③ 属性的封装+魔术方法

private $age;
function get($key){
return $this->$key;
}
function set($key,$value){
$this->$key=$value;
}
$对象->age; // 访问对象私有属性时,自动调用get()魔术方法,并且将访问的属性名传给get()方法;
$对象->age=12; // 设置对象私有属性时,自动调用set()魔术方法,并且将设置的属性名以及属性值传给set()方法;

【 注意】:在魔术方法中,可以使用分支结构,判断$key的不同,进行不同操作。

4、关于封装的魔术方法:

① set($key,$value):给类私有属性赋值时自动调用,调用时给方法传递两个参数:需要设置的属性名、属性值;

② get($key):读取类私有属性时自动调用,调用时给方法传递一个参数:需要读取的属性名;

③ isset($key):外部使用isset()函数检测私有属性时,自动调用。

>>> 类外部使用isset();检测私有属性,默认是检测不到的。false

>>> 所以,我们可以使用isset();函数,在自动调用时,返回内部检测结果。

function isset($key){
  return isset($this->$key);
}
Copy after login

当外部使用isset($对象名->私有属性);检测时,将自动调用上述isset()返回的结果!

④ unset($key):外部使用unset()函数删除私有属性时,自动调用;

function unset($key){
  unset($this->$key);
}
Copy after login

当外部使用unset($对象名->私有属性);删除属性时,自动将属性名传给unset(),并交由这个魔术方法处理。

实例一枚

class Person{
  public $name;
  public $age;
  public $sex;
  function construct($name, $age,$sex){
   $this->name=$name;
   $this->setAge($age);
   $this->setSex($sex);
  }
  function setAge($age){
   if($age>=0&&$age<=120){
   return $this->age=$age;
   }else{
    die("年龄输入有误!!!");
   }
  }
  function setSex($sex){
   if($sex=="女"||$sex=="男"){
   return $this->sex=$sex;
   }else{
    die("性别输入有误!!!");
   }
  }
  function say(){
   echo "我的名字叫{$this->name},我的年龄{$this->age},我的性别是{$this->sex}<br>";
  }
 }
class Work extends Person{private $position;
  function construct($name, $age,$sex,$position){
   parent::construct($name, $age,$sex);
   $this->job=$job;
   $this->setPosition($position);
  }
  function setPosition($position){
   $arr=[&#39;总监&#39;,&#39;董事长&#39;,&#39;程序员&#39;,&#39;清洁工&#39;];
   if(in_array($position, $arr)){
    return $this->position=$position;
   }else{
    die("不存在该职位");
   }
  }  
  function set($key,$value){
   if($key=="age"){
    return parent::setAge($value);
   }
   elseif($key=="sex"){
    return parent::setSex($value);
   }
   elseif($key=="position"){
    return $this->setPosition($value);
   }
   return $this->$key=$value;
  }
  
  function say(){
   parent::say();
   echo "我的职位是{$this->position}";
  }
  }
  
 $zhangsan=new Work("张三",22,"男","总监");
 $zhangsan->setSex("女");
 $zhangsan->setAge(30);
// $zhangsan->setPosition("董事长");
 $zhangsan->position="董事长";
 $zhangsan->name="lisi";
 $zhangsan->say();
Copy after login

三.多态

3.1、什么是多态?

多态实现多态的前提是实现继承。

1.一个类被多个子类继承,如果这个类的某个方法在多个子类中表现出不同的功能,我们称这种行为为多态。在PHP中的方法重写,

2.实现多态的必要途径:

⑴子类继承父类;

⑵重写父类方法;

⑶父类引用指向子类对象;

class Computer{
 function fangfa(InkBox $a,Paper $b){  //父类引用
 echo "即将开始打印····<br>"; 
 $a->color();
 $b->sizes();
 echo "打印结束···<br>"; 
 
 }
}

class Color implements InkBox{
 function color(){
 echo "正在装载彩色墨盒<br>";
 echo "实现彩色墨盒<br>";
 }
}
class White implements InkBox{
 function color(){
 echo "正在装载黑白墨盒<br>"; 
 echo "实现黑白墨盒<br>";
 }
}
class A4 implements Paper{
 function sizes(){
 echo "正在加载A4纸张<br>";
 echo "实现A4纸张<br>";
 }
}
class A5 implements Paper{
 function sizes(){
 echo "实现A5纸张<br>";
 }
}

$com=new Computer();//创建对象
$com->fangfa(new Color(),new A4());//子类对象
Copy after login

相关课程推荐:

视频教程: 韩顺平 2016年 最新PHP面向对象编程视频教程

视频教程: PHP面向对象编程视频教程

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!